JavaScript 数组方法 reduce 的妙用之处

本文展示了JavaScript的reduce方法在数组操作中的几种常见用途,包括数组元素求和、数组扁平化、统计数组元素出现次数、反转字符串、去重以及使用Set进行高效去重。这些示例展示了reduce的灵活性和实用性。
摘要由CSDN通过智能技术生成

1、数组求和-reduce()方法最直接的用法就是对数组元素求和

let total = [34, 12, 143, 13, 76].reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  0
);
console.log(total);
// 结果:278

2、扁平数组

const array = [[0, 1], [2, 3], [4, 5], [5, 6]];

const flattenedArray = array.reduce(
  (previousValue, currentValue) => previousValue.concat(currentValue),
  []
);
console.log(flattenedArray);
// 结果:[0, 1, 2, 3, 4, 5, 5, 6]

3、统计数组元素出现次数

const colors = ['green', 'red', 'red', 'yellow', 'red', 'yellow', 'green', 'green'];

const colorMap = colors.reduce((previousValue, currentValue) => {
    previousValue[currentValue] >= 1 ? previousValue[currentValue]++ : previousValue[currentValue] = 1;
    return previousValue;
  }, 
  {}
);

console.log(colorMap);

结果

{green: 3, red: 3, yellow: 2}

4、反转字符串

const str = 'hello world';
[...str].reduce((a,v) => v + a);  // 输出结果:'dlrow olleh'

5、数组去重

const arr = [1,2,6,5,9,5,1];
const dedupe = (acc, currentValue) => {
  if (!acc.includes(currentValue)) {
    acc.push(currentValue);
  }
  return acc;
};
const dedupedArr = arr.reduce(dedupe, []); 
console.log(dedupedArr); //  [1, 2, 6, 5, 9]

6、用set去重是比较好点的,性能更高,效率好的方法

const arr = [1,2,6,5,9,5,1];
let d = [...new Set(arr)];
console.log(d); // [1, 2, 6, 5, 9]
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JavaScript数组方法reduce()是用于对数组中的元素进行累积计算的方法。它接受一个回调函数作为参数,该回调函数可以定义两个参数:累积器和当前值。reduce()方法遍历数组的所有元素,并将每个元素传递给回调函数进行累积计算。最后,它返回一个累积的结果。 在引用中的示例中,我们可以看到使用reduce()方法来计算数组的和和乘积。通过传递一个回调函数给reduce()方法,在每次迭代中将上一个值与当前值相加或相乘,最终得到累积的和和乘积。 需要注意的是,如果数组是空的,使用reduce()方法会报错。如引用所示,对于空数组reduce()方法需要传入一个初始值作为累积器的初始值,否则会抛出"TypeError: Reduce of empty array with no initial value"的错误。 最后,reduce()方法的语法是array.reduce(function(total, currentValue, currentIndex, arr), initialValue)。其中,total是累积器的初始值或上一次回调函数的返回值,currentValue是当前元素的值,currentIndex是当前元素的索引,arr是原始数组。initialValue是可选的,用于设置累积器的初始值,如果不传递该参数,则默认使用数组的第一个元素作为初始值。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [JavaScript数组reduce()方法详解及奇淫技巧](https://blog.csdn.net/saucxs/article/details/91045557)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [JS数组reduce()方法详解](https://blog.csdn.net/weixin_47619284/article/details/125921346)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值