reduce的使用

定义:

接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。


使用:

// 参数( acc:必填,cur:必填,idx:非必填,arr:非必填)
returnVal = arr.reduce((acc:上一次计算后返回的值,cur:当前值,idx:当前索引,arr:原始数组)=>{},initialVal)

示例:

求和:

const a = [1,2,3,4];
const sum = a.reduce((acc,cur)=>{
    return acc+cur
},0)
console.log(sum)  // 10

复杂场景:

需求:将数组对象按某个属性进行聚合,并且将

例如:

  数组数据根据key进行聚合
  ex:key:day,原始数组[{day:1,cost:1,dk:1},{day:1,cost:2},...] => [{day:1,cost:[1,2],dk:[1,null]},...]

分析:

  • 第一步得计算出原始数组里对象属性的并集
  • 第二步根据第一步计算出的属性列表将原始数据按属性聚合,若原始数据的属性不一致,就要考虑将聚合属性的值补齐
  • 第三步获取聚合后每个属性的最大长度,为补齐做准备
  • 第四步用第三步得到的属性长度补齐第二步得到的聚合数据

好了,分析完做法,下面就是代码编写了

  • 第一步
const allKeys = data.reduce((prev, acc) => {
   const allkeys = Object.keys(acc);
   allkeys.forEach((key) => {
     if (!prev.find((prKey) => prKey === key)) {
       prev.push(key);
     }
   });
   return prev;
 }, []);
 // 获取非key之外的所有属性名称
 const keys = allKeys.filter((itm) => itm !== key);
  • 第二步(这里我先聚合成一个对象,再通过Object.values去转为数组,也可以直接聚合为数组,对象的好处是属性不会重复)
const initData = Object.values(
   data.reduce((acc, cur) => {
     if (acc[cur[key]]) {
       keys.forEach((itm) => {
         acc[cur[key]][itm].push(cur[itm]);
       });
     } else {
       const itemData = {
         [key]: cur[key]
       };
       keys.forEach((itm) => {
         itemData[itm] = [cur[itm]];
       });
       acc[cur[key]] = itemData;
     }
     return acc;
   }, {})
 );
  • 第三步
const keyForLen = keys.reduce((acc, cur) => {
   let maxLen = 0;
   initData.forEach((itm) => {
     maxLen = itm[cur].length > maxLen ? itm[cur].length : maxLen;
   });
   acc[cur] = maxLen;
   return acc;
 }, {});
  • 第四步
const finalData =  initData.map((item) => {
  keys.forEach((itm) => {
    const needFillNum = keyForLen[itm] - (item[itm].length || 0);
    if (needFillNum > 0) {
      item[itm] = [...item[itm], ...[...new Array(needFillNum)].map(() => null)];
    }
  });
  return item;
}) || [] 

前面就是分解步骤的关键代码,下面是完整代码

const getJsonArrKeys = (jsonArr) => {
    if (!(jsonArr instanceof Array)) return;
    return jsonArr.reduce((prev, acc) => {
      const allkeys = Object.keys(acc);
      allkeys.forEach((key) => {
        if (!prev.find((prKey) => prKey === key)) {
          prev.push(key);
        }
      });
      return prev;
    }, []);
  };
  const formatChartArr = (data, key) => {
    // 获取非key之外的所有属性名称
    const keys = getJsonArrKeys(data).filter((itm) => itm !== key);
    // 初始化聚合数组数据
    const initData = Object.values(
      data.reduce((acc, cur) => {
        if (acc[cur[key]]) {
          keys.forEach((itm) => {
            acc[cur[key]][itm].push(cur[itm]);
          });
        } else {
          const itemData = {
            [key]: cur[key]
          };
          keys.forEach((itm) => {
            itemData[itm] = [cur[itm]];
          });
          acc[cur[key]] = itemData;
        }
        return acc;
      }, {})
    );
    // 聚合数据各属性的最大长度
    const keyForLen = keys.reduce((acc, cur) => {
      let maxLen = 0;
      initData.forEach((itm) => {
        maxLen = itm[cur].length > maxLen ? itm[cur].length : maxLen;
      });
      acc[cur] = maxLen;
      return acc;
    }, {});
    // 根据属性最大长度补齐聚合数据
    return (
      initData.map((item) => {
        keys.forEach((itm) => {
          const needFillNum = keyForLen[itm] - (item[itm].length || 0);
          if (needFillNum > 0) {
            item[itm] = [...item[itm], ...[...new Array(needFillNum)].map(() => null)];
          }
        });
        return item;
      }) || []
    );
  };
`reduce()` 是 JavaScript 中数组的一个非常强大且灵活的方法,用于将数组中的元素依次累积为一个最终值。它可以用来求和、拼接字符串、分组数据等。 --- ### 一、基本语法 ```javascript array.reduce((accumulator, currentValue, currentIndex, array) => { // 返回新的 accumulator 值 }, initialValue) ``` - `accumulator`: 累积器,上一次调用回调返回的值或初始值。 - `currentValue`: 当前处理的元素。 - `currentIndex`(可选): 当前处理的索引。 - `array`(可选): 调用 `reduce` 的数组。 - `initialValue`(可选): 初始值。如果未提供,则使用数组第一个元素作为初始值。 --- ### 二、常见使用场景及示例代码 #### 1. 求和 ```javascript const numbers = [1, 2, 3, 4]; const sum = numbers.reduce((acc, curr) => acc + curr, 0); console.log(sum); // 输出: 10 ``` **解释:** - 初始值是 `0`。 - 每次循环累加当前值到 `acc` 上。 --- #### 2. 数组扁平化 ```javascript const nested = [[1, 2], [3, 4], [5]]; const flat = nested.reduce((acc, curr) => acc.concat(curr), []); console.log(flat); // 输出: [1, 2, 3, 4, 5] ``` **解释:** - 使用 `concat` 合并子数组。 --- #### 3. 统计数组中元素出现次数 ```javascript const fruits = ['apple', 'banana', 'apple', 'orange']; const count = fruits.reduce((acc, fruit) => { acc[fruit] = (acc[fruit] || 0) + 1; return acc; }, {}); console.log(count); // 输出: { apple: 2, banana: 1, orange: 1 } ``` **解释:** - 使用对象记录每个水果出现的次数。 --- #### 4. 按条件分组 ```javascript const people = [ { name: 'Alice', age: 20 }, { name: 'Bob', age: 30 }, { name: 'Eve', age: 20 } ]; const grouped = people.reduce((acc, person) => { const key = person.age; if (!acc[key]) { acc[key] = []; } acc[key].push(person); return acc; }, {}); console.log(grouped); /* 输出: { '20': [{name: 'Alice', age: 20}, {name: 'Eve', age: 20}], '30': [{name: 'Bob', age: 30}] } */ ``` --- #### 5. 实现链式调用(组合函数) ```javascript const add = x => y => y + x; const multiply = x => y => y * x; const operations = [add(5), multiply(2), add(10)]; const result = operations.reduce((acc, fn) => fn(acc), 5); console.log(result); // ((5 + 5) * 2) + 10 = 30 ``` --- ### 三、注意事项 - 如果不传 `initialValue`,则第一次执行回调时会跳过第一个元素,从第二个开始。 - 如果数组为空且没有提供 `initialValue`,会抛出错误。 - `reduce()` 可以替代 `map()` 和 `filter()`,但为了代码清晰建议还是分开使用。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值