js数组reduce详解

reduce() 是 JavaScript 数组中的一个高阶函数,它用于对数组中的所有元素执行一个给定的累加器函数,并最终返回一个单一的值。reduce() 可以用于数组的求和、对象合并、数组去重等多种操作。

语法:

array.reduce((accumulator, currentValue, currentIndex, array) => {
  // 函数体
}, initialValue);

参数:

  1. callback 函数

    • accumulator:累加器,存储上一次调用 callback 时返回的值,或是初始值。
    • currentValue:当前正在处理的数组元素。
    • currentIndex:当前元素的索引(可选)。
    • array:调用 reduce() 的数组本身(可选)。
  2. initialValue(可选):累加器的初始值。如果没有提供 initialValue,则数组的第一个元素将作为累加器的初始值,currentValue 从数组的第二个元素开始。

工作原理:

  • reduce() 依次对数组中的每个元素调用 callback 函数,使用上一次调用 callback 返回的值作为 accumulator,结合当前元素的值来计算出一个新的值,最终累加成一个单一的输出。

示例 1:数组求和

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

解释

  • initialValue0accumulator 的初始值为 0,之后逐步将每个数组元素累加。

示例 2:数组最大值

const numbers = [1, 5, 3, 9, 2];
const max = numbers.reduce((accumulator, currentValue) => {
  return currentValue > accumulator ? currentValue : accumulator;
}, numbers[0]);
console.log(max); // 输出 9

解释

  • 使用 reduce() 找出数组中的最大值,accumulator 开始为数组的第一个值,并逐步与当前值比较,保留更大的值。

示例 3:将二维数组拍平

const array = [[1, 2], [3, 4], [5, 6]];
const flatArray = array.reduce((accumulator, currentValue) => {
  return accumulator.concat(currentValue);
}, []);
console.log(flatArray); // 输出 [1, 2, 3, 4, 5, 6]

解释

  • reduce() 将二维数组扁平化,将每个子数组连接到 accumulator 中。

示例 4:统计数组中元素出现的次数

const fruits = ['apple', 'banana', 'orange', 'apple', 'orange', 'banana', 'banana'];
const count = fruits.reduce((accumulator, fruit) => {
  accumulator[fruit] = (accumulator[fruit] || 0) + 1;
  return accumulator;
}, {});
console.log(count); // 输出 { apple: 2, banana: 3, orange: 2 }

解释

  • 通过 reduce() 累积每个元素的出现次数,accumulator 是一个对象,用于存储每个水果的数量。

示例 5:对象数组求和

假设我们有一个对象数组,想对其中某个属性进行求和:

const products = [
  { name: 'Laptop', price: 1000 },
  { name: 'Phone', price: 500 },
  { name: 'Tablet', price: 750 }
];
const total = products.reduce((accumulator, product) => {
  return accumulator + product.price;
}, 0);
console.log(total); // 输出 2250

解释

  • 对象数组中的 price 属性相加,得到总价格。

总结:

reduce() 是一个非常强大且灵活的数组方法,它能够通过不断累计处理数组元素,生成单一的结果。根据不同的初始值和处理逻辑,reduce() 可以用于各种任务,如求和、去重、分组、累积等等。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值