reduce函数的使用

200 阅读2分钟

1.reduce方法介绍

arr.reduce(callback(previousValue, currentValue, currentIndex, array), initialValue)

reduce函数接收两个参数:

  • callback回调函数 此回调函数分别包含了四个参数:

    • previousValue:上一次调用 callbackFn 时的返回值。在第一次调用时,若指定了初始值 initialValue,其值则为 initialValue,否则为数组索引为 0 的元素 array[0]
    • currentValue:数组中正在处理的元素。在第一次调用时,若指定了初始值 initialValue,其值则为数组索引为 0 的元素 array[0],否则为 array[1]
    • currentIndex:数组中正在处理的元素的索引。若指定了初始值 initialValue,则起始索引号为 0,否则从索引 1 起始。
    • array:用于遍历的数组
  • initialValue初始值( 可选参数 )

    • 作为第一次调用 callback 函数时参数 previousValue 的值。若指定了初始值 initialValue,则 currentValue 则将使用数组第一个元素;否则 previousValue 将使用数组第一个元素,而 currentValue 将使用数组第二个元素。

image.png

2.使用场景举例

  1. 拼接字符串数组

const message = ["JavaScript ", "is ", "fun."];

function joinStrings(previousValue, currentValue) {
  return previousValue + currentValue;
}

let joinedString = message.reduce(joinStrings);
console.log(joinedString);

// 输出: JavaScript is fun.

  1. 对数组中的值进行相加
const numbers = [1, 2, 3, 4, 5, 6];

let summation = numbers.reduce(
  (previousValue, currentValue) => previousValue + currentValue
);
console.log(summation);

// 输出: 21
  1. 数组去重
let ageGroup = [18, 21, 1, 1, 51, 18, 21, 5, 18, 7, 10];
let uniqueAgeGroup = ageGroup.reduce((previousValue, currentValue) => {
    if(previousValue.indexOf(currentValue) === -1) {
        previousValue.push(currentValue)
    }
    return previousValue
}, [])

console.log(uniqueAgeGroup)
    
// 输出: [18, 21,  1, 51, 5,  7, 10]
  1. 按对象的属性对数据进行分组
let people = [
    { name: "John", age: 21 },
    { name: "Oliver", age: 55 },
    { name: "Michael", age: 55 },
    { name: "Dwight", age: 19 },
    { name: "Oscar", age: 21 },
    { name: "Kevin", age: 55 },
];
const groupBy = (objectArray, property) => {
    return objectArray.reduce((previousValue, currentValue) => {
        let key = currentValue[property];
        if(!previousValue[key]) {
            previousValue[key] = [];
        }
        previousValue[key].push(currentValue);
        return previousValue
    }, {})
}
let groupedPeople = groupBy(people, "age");

console.log(groupedPeople)

// 输出: 
// {
//     '19': [ { name: 'Dwight', age: 19 } ],
//     '21': [ { name: 'John', age: 21 }, { name: 'Oscar', age: 21 } ],
//     '55': [
//       { name: 'Oliver', age: 55 },
//       { name: 'Michael', age: 55 },
//       { name: 'Kevin', age: 55 }
//     ]
// }