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
               ↑
               最终结果
相关推荐
kevin_水滴石穿6 小时前
docker-compose.yml案例
java·服务器·开发语言
coderxiaohan6 小时前
【C++】用哈希表封装unordered_map和unordered_set
开发语言·c++·散列表
代码or搬砖6 小时前
ES6新增的新特性以及用法
前端·javascript·es6
小番茄夫斯基6 小时前
Monorepo 架构:现代软件开发的代码管理革命
前端·javascript·架构
清水白石0086 小时前
《Python 分布式锁全景解析:从基础原理到实战最佳实践》
开发语言·分布式·python
前端世界6 小时前
从“看不懂”到“能用”:一次搞清 C 语言指针数组
c语言·开发语言
gao_shengping6 小时前
Queue(队列)两组增删查操作的区别
java·开发语言
weixin_307779136 小时前
Jenkins Pipeline: Multibranch 插件详解:现代CI/CD的多分支管理利器
运维·开发语言·自动化·jenkins·etl
Da Da 泓6 小时前
多线程(四)【线程安全问题】
java·开发语言·jvm·学习·安全·多线程·线程安全问题