js的reduce详解

养成良好习惯,每日记录一个方法的使用

javascript 复制代码
array.reduce(callback(accumulator, currentValue, currentIndex, array), initialValue)

1. 回调函数 callback

接收四个参数:

  • accumulator (acc):累积器,累积回调函数的返回值

  • currentValue (cur):当前正在处理的元素

  • currentIndex (idx):当前元素的索引(可选)

  • array (src):调用 reduce 的数组(可选)

2. initialValue

作为第一次调用回调函数时的 accumulator 的初始值(可选)。如果未提供,则使用数组的第一个元素作为初始值,从第二个元素开始处理。

javascript 复制代码
const numbers = [1, 2, 3, 4, 5];

// 无初始值
const sum1 = numbers.reduce((acc, cur) => acc + cur);
console.log(sum1); // 15

// 有初始值
const sum2 = numbers.reduce((acc, cur) => acc + cur, 0);
console.log(sum2); // 15

数组扁平化
const nestedArray = [[1, 2], [3, 4], [5, 6]];
const flatArray = nestedArray.reduce((acc, cur) => acc.concat(cur), []);
console.log(flatArray); // [1, 2, 3, 4, 5, 6]


统计元素出现次数
const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana'];
const count = fruits.reduce((acc, fruit) => {
  acc[fruit] = (acc[fruit] || 0) + 1;
  return acc;
}, {});
console.log(count);
// { apple: 2, banana: 3, orange: 1 }

按属性分组
const people = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 25 },
  { name: 'David', age: 30 }
];

const groupedByAge = people.reduce((acc, person) => {
  const key = person.age;
  if (!acc[key]) {
    acc[key] = [];
  }
  acc[key].push(person);
  return acc;
}, {});

console.log(groupedByAge);
// {
//   25: [{ name: 'Alice', age: 25 }, { name: 'Charlie', age: 25 }],
//   30: [{ name: 'Bob', age: 30 }, { name: 'David', age: 30 }]
// }

管道函数组合
const add5 = x => x + 5;
const multiply3 = x => x * 3;
const subtract2 = x => x - 2;

const compose = (...fns) => initialValue => 
  fns.reduce((acc, fn) => fn(acc), initialValue);

const transform = compose(add5, multiply3, subtract2);
console.log(transform(10)); // 43

其中acc就是累加器

javascript 复制代码
const items = [
  { price: 10, quantity: 2 },  // 20元
  { price: 5, quantity: 3 },   // 15元
  { price: 8, quantity: 1 }     // 8元
];

const total = items.reduce((acc, item) => 
  acc + (item.price * item.quantity), 0);


初始状态:acc = 0
↓
遍历 items[0]: acc = 0 + (10 * 2) = 20
               ↑
               新的 acc
↓
遍历 items[1]: acc = 20 + (5 * 3) = 35
               ↑
               新的 acc
↓
遍历 items[2]: acc = 35 + (8 * 1) = 43
               ↑
               最终结果
相关推荐
2401_8769075219 分钟前
USB TYPE-C 公头连接器设计规范总结:提升可靠性、降本增效的关键指南
c语言·开发语言·设计规范
额呃呃23 分钟前
std::allocator<T>::destroy
开发语言
期待のcode28 分钟前
Java虚拟机栈
java·开发语言·jvm
cute_ming31 分钟前
关于基于nodeMap重构DOM的最佳实践
java·javascript·重构
码途潇潇1 小时前
JavaScript 中 ==、===、Object.is 以及 null、undefined、undeclared 的区别
前端·javascript
iso少年1 小时前
Go 语言并发编程核心与用法
开发语言·后端·golang
故事不长丨1 小时前
C#字典(Dictionary)全面解析:从基础用法到实战优化
开发语言·c#·wpf·哈希算法·字典·dictionary·键值对
Sun_小杰杰哇1 小时前
Dayjs常用操作使用
开发语言·前端·javascript·typescript·vue·reactjs·anti-design-vue
雒珣1 小时前
Qt简单任务的多线程操作(无需创建类)
开发语言·qt
basestone1 小时前
🚀 从重复 CRUD 到工程化封装:我是如何设计 useTableList 统一列表逻辑的
javascript·react.js·ant design