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
               ↑
               最终结果
相关推荐
灰子学技术4 小时前
go response.Body.close()导致连接异常处理
开发语言·后端·golang
二十雨辰4 小时前
[python]-AI大模型
开发语言·人工智能·python
Yvonne爱编码5 小时前
JAVA数据结构 DAY6-栈和队列
java·开发语言·数据结构·python
Re.不晚5 小时前
JAVA进阶之路——无奖问答挑战1
java·开发语言
Daniel李华5 小时前
echarts使用案例
android·javascript·echarts
北原_春希5 小时前
如何在Vue3项目中引入并使用Echarts图表
前端·javascript·echarts
JY-HPS5 小时前
echarts天气折线图
javascript·vue.js·echarts
你这个代码我看不懂5 小时前
@ConditionalOnProperty不直接使用松绑定规则
java·开发语言
尽意啊5 小时前
echarts树图动态添加子节点
前端·javascript·echarts
吃面必吃蒜5 小时前
echarts 极坐标柱状图 如何定义柱子颜色
前端·javascript·echarts