记录:JS reduce()使用场景

5 阅读1分钟

本文摘抄ai

基本语法

array.reduce((accumulator, currentValue, index, array) => { 
    // 执行逻辑 
    return accumulator; // 必须返回累加器的新值 
}, initialValue);
  • accumulator (累加器) : 上一次回调函数返回的值。如果是第一次执行且有初始值,则为初始值。

  • currentValue (当前值) : 当前正在处理的数组元素。

  • index (可选) : 当前元素的索引。

  • array (可选) : 调用 reduce 的原数组。

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

    • 如果提供了accumulator 从该值开始,currentValue 从数组第一个元素开始。
    • 如果未提供accumulator 默认为数组第一个元素,currentValue 从数组第二个元素开始。注意:如果数组为空且未提供初始值,会报错。

场景一:求和

const numbers = [1, 2, 3, 4, 5]; 
const sum = numbers.reduce((acc, curr) => { 
    return acc + curr; 
}, 0); // 初始值为 0 

console.log(sum); // 输出: 15

场景二:扁平化二维数组

const nested = [[1, 2], [3, 4], [5, 6]]; 
const flat = nested.reduce((acc, curr) => { 
    return acc.concat(curr); 
}, []); // 初始值为空数组 

console.log(flat); // [1, 2, 3, 4, 5, 6]

注意:concat性能较大,生产建议使用push方法。

场景三:统计元素出现次数(转为对象)

const words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']; 
const count = words.reduce((acc, curr) => { 
    if (acc[curr]) { 
        acc[curr]++; 
    } else { 
        acc[curr] = 1; 
    } return acc; 
}, {}); // 初始值为空对象 

console.log(count); // 输出: { apple: 3, banana: 2, orange: 1 }

场景四:数组去重

const nums = [1, 2, 2, 3, 4, 4, 5]; 
const unique = nums.reduce((acc, curr) => { 
    if (!acc.includes(curr)) { 
        acc.push(curr); 
    } 
    return acc; 
}, []); 

console.log(unique); // [1, 2, 3, 4, 5]