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
               ↑
               最终结果
相关推荐
前端Hardy29 分钟前
HTML&CSS&JS:打造丝滑的3D彩纸飘落特效
前端·javascript·css
前端Hardy29 分钟前
HTML&CSS&JS:丝滑无卡顿的明暗主题切换
javascript·css·html
UIUV2 小时前
node:child_process spawn 模块学习笔记
javascript·后端·node.js
烛阴3 小时前
Three.js 零基础入门:手把手打造交互式 3D 几何体展示系统
javascript·webgl·three.js
颜酱3 小时前
单调栈:从模板到实战
javascript·后端·算法
_AaronWong5 小时前
Electron 实现仿豆包划词取词功能:从 AI 生成到落地踩坑记
前端·javascript·vue.js
JohnYan6 小时前
工作笔记-CodeBuddy应用探索
javascript·ai编程·aiops
wuhen_n6 小时前
双端 Diff 算法详解
前端·javascript·vue.js
光影少年6 小时前
说说闭包的理解和应用场景?
前端·javascript·掘金·金石计划
爱勇宝6 小时前
别再混用了!import.meta.env 与 process.env 的本质差异一次讲透
前端·javascript·vue.js