Reduce()

2023/5/10

# 1.reduce简介

语法:

arr.reduce(callback(accumulator, currentValue[, currentIndex[, array]])[, initialValue]);

其中callback可以接受四个参数:

  • accumulator:累加器,它存储了上一次回调函数的返回值,或者是 initialValue 的值(如果指定了的话)。
  • currentValue:当前数组元素的值。
  • currentIndex:当前数组元素的索引
  • array:原数组
  • initialValue:指定的初始值,如果不指定 initialValue,那么累加器的初始值将会是数组中的第一个元素。

# 2.reduce技巧

//1.计算元素出现的次数
const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
const fruitsCount = fruits.reduce((accumulator,currentValue)=>{
    accumulator[currentValue] = (accumulator[currentValue] || 0) +1;
    //通过 accumulator[currentValue] 来获取对象中指定键名对应的值。
    //如果这个键名不存在,则使用逻辑或运算符 || 来设置默认值为 0。
    //然后将这个值加 1,表示出现次数加 1。
    //最后将更新后的值重新赋值给对象的属性 accumulator[currentValue],实现累加统计的效果。
    return accumulator;
},{})

//2.数组扁平化
const array = [[1,2],[2,3],[4,5]];
const flatArray = array.reduce((accumulator,currentValue)=>{
    accumulator = [...accumulator,...currentValue]
    return accumulator;
},[])

//3.条件分组(根据age)
const people = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 },
  { name: 'David', age: 25 },
  { name: 'Emily', age: 30 }
];
const groupedPeople  = people.reduce((accumulator,currentValue)=>{
    const key = currentValue.age
    if(!accumulator[key]){
        accumulator[key] = []
    }
    accumulator[key].push(currentValue) 
    return accumulator
},{})

//4.数组合并
const keys = ['name', 'age', 'gender'];
const values = ['Alice', 25, 'female'];
const person = keys.reduce((accumulator, currentValue, index) => {
    accumulator[currentValue] = values[index];
    return accumulator;
}, {});

# 3.reduce手写

function myReduce(array, callback, initialValue) {
  // 如果提供了初始值,则将它赋值给累加器;否则,将第一个元素赋值给累加器
  let accumulator = initialValue === undefined ? undefined : initialValue;

  // 遍历数组中的每个元素
  for (let i = 0; i < array.length; i++) {
    // 如果累加器有值,则将它与当前元素一起传递给回调函数计算,并将结果赋值给累加器
    if (accumulator !== undefined) {
      accumulator = callback(accumulator, array[i], i, array);
    } else {
      // 如果累加器没有值,则将当前元素赋值给累加器
      accumulator = array[i];
    }
  }

  // 返回最终的累加器值
  return accumulator;
}