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
               ↑
               最终结果
相关推荐
四维碎片几秒前
【Qt】代理(Delegate)的使用
开发语言·qt
我是伪码农3 分钟前
Vue 1.28
前端·javascript·vue.js
鹓于7 分钟前
Excel一键生成炫彩二维码
开发语言·前端·javascript
siwangdexie_new7 分钟前
html格式字符串转word文档,前端插件( html-docx-js )遇到兼容问题的解决过程
前端·javascript·html
froginwe119 分钟前
MongoDB 固定集合详解
开发语言
m0_7369191021 分钟前
C++中的策略模式实战
开发语言·c++·算法
子春一21 分钟前
Flutter for OpenHarmony:构建一个智能长度单位转换器,深入解析 Flutter 中的多字段联动、输入同步与工程化表单设计
开发语言·javascript·flutter
利刃大大25 分钟前
【Vue】scoped作用 && 父子组件通信 && props && emit
前端·javascript·vue.js
从此不归路28 分钟前
Qt5 进阶【9】模型-视图框架实战:从 TableView 到自定义模型的一整套落地方案
开发语言·c++·qt
-凌凌漆-33 分钟前
【Vue】Vue3 vite build 之后空白
前端·javascript·vue.js