likes
comments
collection
share

数组累计运算的最强函数:Array.reduce

作者站长头像
站长
· 阅读数 20

Array.reduce简介

各位小伙伴好~今天给大家带来JavaScript 中的数组的reduce 方法详解。

我刚学习前端不久,所以技术上比较菜,有问题大家请温柔指教~

Array.prototype.reduce 方法是一个非常强大且常用的数组方法,它可以帮助我们对数组中的每一个元素进行累积运算,从而将数组简化为单一的输出值。比如,用它可以方便的对数组的某个字段进行遍历求和。

语法简介

array.reduce(fn,initValue)

reduce(fn,initValue)接收2个参数。

第一个是迭代器函数,函数的作用是对数组中从左到右的每一个元素进行处理。函数有4个参数,分别是accumulator、currentValue、index、array。

属性名属性含义
accumulator累加器,即函数上一次调用的返回值。第一次的时候为 initialValuearr[0]
currentValue数组中函数正在处理的的值第一次的时候initialValuearr[1]
index数组中函数正在处理的的索引
array函数调用的数组

reduce 的第二个参数initValue,为累加器的初始值。没有时,累加器第一次的值为currentValue;

基础使用示例

演示下它最基本的用法:计算数组元素的总和:

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);

console.log(sum); // 输出:15

在上述示例中,reduce 方法通过将每个元素依次加到累计器 accumulator 上,最终得到了数组元素的总和 15

其他使用场景

下面是我整理的一些其他使用场景,欢迎大家补充完善。

对象数组求和

计算购物车中所有商品的总价:

const cart = [
  { name: '华为手表', price: 899.99 },
  { name: '小米手表', price: 499.99 },
  { name: '平果手表', price: 299.99 }
];

const totalPrice = cart.reduce((acc, item) => acc + item.price, 0);
console.log(totalPrice); // 输出:1699.97

数组扁平化

将一个多维数组转换为一维数组:

const nestedArray = [[1, 2], [3, 4], [5, 6]];
const flatArray = nestedArray.reduce((acc, currentValue) => acc.concat(currentValue), []);
console.log(flatArray); // 输出:[1, 2, 3, 4, 5, 6]

这个不常用,扁平化有很多其他方法。

统计元素出现次数

统计数组中每个元素出现的次数:

const fruits = ['小米', '华为', '苹果', '小米', '苹果', '华为', '华为'];

const fruitCount = fruits.reduce((acc, device) => {
  acc[device] = (acc[device] || 0) + 1;
  return acc;
}, {});
console.log(fruitCount); 
// 输出:{ 小米: 2, 华为: 3, 苹果: 2 }

查找最大值或最小值

找出数组中的最大值或最小值:

const numbers = [10, 5, 20, 8, 15];
const max = numbers.reduce((acc, num) => Math.max(acc, num), numbers[0]);
console.log(max); // 输出:20

const min = numbers.reduce((acc, num) => Math.min(acc, num), numbers[0]);
console.log(min); // 输出:5

其实找最大最小值,有好多方法可以用,这个只是一种

总结

Array.prototype.reduce 方法是一个非常好用的函数,无论是进行简单的累加操作,还是处理更复杂的数据结构,大家快用起来吧~

是小姐姐不是小哥哥~

转载自:https://juejin.cn/post/7393195128955469858
评论
请登录