前端 | JavaScript中的reduce方法

[复制链接]
发表于 2025-4-3 05:39:57 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
1. 什么是reduce

reduce 方法是 JavaScript 中数组的重要方法之一,用于对数组中的元素进行累积盘算。它接收一个回调函数作为参数,并返回一个终极盘算效果。reduce 在很多场景下都非常有效,比如求和、数组扁平化、对象计数、数据转换等。
2. reduce语法

2.1 语法

arr.reduce(callback, initialValue)
2.2 参数说明


  • callback(accumulator, currentValue, currentIndex, array):回调函数,接受四个参数:

    • accumulator:上一次callback执行后的返回值
    • currentValue:当前值
    • currentIndex:当前元素在数组中的索引
    • array:原数组(正在遍历的数组)

  • initialValue(可选):累加器的初始值

    • 如果提供,则accumulator从initialValue开始
    • 如果没有提供,则取数组的第一个元素

3. reduce执行过程

3.1 执行过程

reduce 方法会遍历数组的每个元素,并对其应用回调函数。其执行流程如下:

  • 初始化 accumulator:如果提供了 initialValue,则 accumulator 取 initialValue,否则取数组的第一个元素,并跳过该元素。
  • 遍历数组:从索引 0(如果有 initialValue)或 1(如果没有 initialValue)开始,依次执行 callback,并更新 accumulator。
  • 返回终极的 accumulator 值。
3.2 示例

  1. const numbers = [1, 2, 3, 4];
  2. const result = numbers.reduce((acc, cur, index) => {
  3.   console.log(`累加器: ${acc}, 当前值: ${cur}, 索引: ${index}`);
  4.   return acc + cur;
  5. }, 0);
  6. console.log('最终结果:', result);
复制代码
执行效果如下:
  1. 累加器: 0, 当前值: 1, 索引: 0
  2. 累加器: 1, 当前值: 2, 索引: 1
  3. 累加器: 3, 当前值: 3, 索引: 2
  4. 累加器: 6, 当前值: 4, 索引: 3
  5. 最终结果: 10
复制代码
4. reduce使用场景

4.1 数组求和

  1. const numbers = [1, 2, 3, 4, 5];
  2. const sum = numbers.reduce((acc, cur) => acc + cur, 0);
  3. console.log(sum); // 输出 15
复制代码
4.2 统计数组中元素出现的次数

  1. const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
  2. const count = fruits.reduce((acc, fruit) => {
  3.   acc[fruit] = (acc[fruit] || 0) + 1;
  4.   return acc;
  5. }, {});
  6. console.log(count); // { apple: 3, banana: 2, orange: 1 }
复制代码
4.3 盘算数组中对象的某个属性总和

  1. const products = [
  2.   { name: 'Laptop', price: 1000 },
  3.   { name: 'Phone', price: 500 },
  4.   { name: 'Tablet', price: 300 }
  5. ];
  6. const totalPrice = products.reduce((acc, product) => acc + product.price, 0);
  7. console.log(totalPrice); // 输出 1800
复制代码
5. reduce进阶用法

5.1 按属性分组数据

  1. const people = [
  2.   { name: 'Alice', age: 25 },
  3.   { name: 'Bob', age: 30 },
  4.   { name: 'Charlie', age: 25 },
  5.   { name: 'David', age: 30 }
  6. ];
  7. const groupedByAge = people.reduce((acc, person) => {
  8.   (acc[person.age] = acc[person.age] || []).push(person);
  9.   return acc;
  10. }, {});
  11. console.log(groupedByAge);
  12. // 输出:
  13. // {
  14. //   25: [{ name: 'Alice', age: 25 }, { name: 'Charlie', age: 25 }],
  15. //   30: [{ name: 'Bob', age: 30 }, { name: 'David', age: 30 }]
  16. // }
复制代码
5.2 盘算嵌套对象的总和

  1. const orders = [
  2.   { customer: 'Alice', total: 50 },
  3.   { customer: 'Bob', total: 30 },
  4.   { customer: 'Alice', total: 20 }
  5. ];
  6. const customerTotals = orders.reduce((acc, order) => {
  7.   acc[order.customer] = (acc[order.customer] || 0) + order.total;
  8.   return acc;
  9. }, {});
  10. console.log(customerTotals);
  11. // 输出:{ Alice: 70, Bob: 30 }
复制代码
5.3 组合多个reduce进行复杂盘算

  1. const data = [
  2.   { category: 'A', value: 10 },
  3.   { category: 'B', value: 20 },
  4.   { category: 'A', value: 15 },
  5.   { category: 'B', value: 25 }
  6. ];
  7. const aggregatedData = data.reduce((acc, item) => {
  8.   acc[item.category] = (acc[item.category] || []).concat(item.value);
  9.   return acc;
  10. }, {});
  11. const summedData = Object.keys(aggregatedData).reduce((acc, key) => {
  12.   acc[key] = aggregatedData[key].reduce((sum, num) => sum + num, 0);
  13.   return acc;
  14. }, {});
  15. console.log(summedData); // 输出:{ A: 25, B: 45 }
复制代码
6. 手写reduce实现

  1. Array.prototype.myReduce = function(callback,initialValue){
  2.     const arr = this;    // 获取调用reduce的数组
  3.    
  4.     if(typeof callback !== "function"){    // 验证回调函数是否传入
  5.         throw new TypeError(`${callback} is not a function`);
  6.     }
  7.    
  8.     let accumulator;    // 累加器
  9.     let startIndex;    // 数组遍历起始位置
  10.     if(initialValue!==undefined){    // 判断是否传递了初始值
  11.         accumulator = initialValue;
  12.         startIndex = 0;
  13.     }else{
  14.         // 如果没有提供初始值,则将第一个数组元素作为累加器的初始值
  15.         if(arr.length===0){
  16.             throw new TypeError(`Reduce of empty array with on initial value`);
  17.         }
  18.         accumulator = arr[0];
  19.         startIndex = 1;
  20.     }
  21.     // 遍历数组并应用回调函数
  22.     for(let i=startIndex;i<arr.length;i++){
  23.         accumulator = callback(accumulator,arr[i],i,arr);
  24.     }
  25.     // 返回累加结果
  26.     return accumulator
  27. }
  28. const numbers = [1,2,3,4,5];
  29. const sum = numbers.myReduce((acc,curr)=>acc+curr,0)   // 15
  30. const product = numbers.myReduce((acc,curr)=>acc*curr)   // 120
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
继续阅读请点击广告
回复

使用道具 举报

×
登录参与点评抽奖,加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表