reduce实用范例

语法

arr.reduce(callback[, initialValue])

reduce为数组中的每一个元素依次执行callback函数,不包括数组中被删除或从未被赋值的元素,接受四个参数:

  • accumulator累计器
  • currentValue当前值
  • currentIndex当前索引
  • array数组

initialValue作为第一次调用 callback函数时的第一个参数的值。 如果没有提供初始值,则将使用数组中的第一个元素。 在没有初始值的空数组,initialValue必须定义,否则会报错。

实用案例

  • 数组去重

    1
    2
    3
    4
    5
    6
    7
    8
    9
    > let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4];
    > let result = arr.sort().reduce((init, current)=>{
    > if(init.length===0 || init[init.length-1]!==current){
    > init.push(current);
    > }
    > return init;
    > }, []);
    > console.log(result); //[1,2,3,4,5]
    >
  • 对象数组去重

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    > var people = [
    > { name: 'Alice', age: 21 },
    > { name: 'Max', age: 20 },
    > { name: 'Jane', age: 20 },
    > { name: 'Alice', age: 21 },
    > ];
    >
    > function dereplication(arr, property) {
    > // 对象数组去重
    > const hash = {};
    > const result = arr.reduce(function(item, next) {
    > hash[next[property]] ? '' : (hash[next[property]] = true && item.push(next));
    > return item;
    > }, []);
    > return result;
    > }
    >
    > var res = dereplication(people, 'name');// 将name属性作为唯一性识别标志
    > // res is:
    > //[
    > // { name: 'Alice', age: 21 },
    > // { name: 'Max', age: 20 },
    > // { name: 'Jane', age: 20 },
    > //]
    >
  • 数组里所有值的和

    1
    2
    3
    4
    5
    > var sum = [0, 1, 2, 3].reduce(function (a, b) {
    > return a + b;
    > }, 0);
    > // sum is 6
    >

    >
    >

  • 累加对象数组里的值

    1
    2
    3
    4
    5
    6
    7
    > var initialValue = 0;
    > var sum = [{x: 1}, {x:2}, {x:3}].reduce(function (accumulator, currentValue) {
    > return accumulator + currentValue.x;
    > },initialValue)
    >
    > console.log(sum) // logs 6
    >
  • 将二维数组转化为一维

    1
    2
    3
    4
    5
    6
    7
    8
    > var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
    > function(a, b) {
    > return a.concat(b);
    > },
    > []
    > );
    > // flattened is [0, 1, 2, 3, 4, 5]
    >
  • 计算数组中每个元素出现的次数

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    > var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
    >
    > var countedNames = names.reduce(function (allNames, name) {
    > if (name in allNames) {
    > allNames[name]++;
    > }
    > else {
    > allNames[name] = 1;
    > }
    > return allNames;
    > }, {});
    > // countedNames is:
    > // { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
    >
  • 按属性对object分类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    > var people = [
    > { name: 'Alice', age: 21 },
    > { name: 'Max', age: 20 },
    > { name: 'Jane', age: 20 }
    > ];
    >
    > function groupBy(objectArray, property) {
    > return objectArray.reduce(function (acc, obj) {
    > var key = obj[property];
    > if (!acc[key]) {
    > acc[key] = [];
    > }
    > acc[key].push(obj);
    > return acc;
    > }, {});
    > }
    >
    > var groupedPeople = groupBy(people, 'age');
    > // groupedPeople is:
    > // {
    > // 20: [
    > // { name: 'Max', age: 20 },
    > // { name: 'Jane', age: 20 }
    > // ],
    > // 21: [{ name: 'Alice', age: 21 }]
    > // }
    >
  • 使用扩展运算符和initialValue绑定包含在对象数组中的数组

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    > // friends - 对象数组
    > // where object field "books" - list of favorite books
    > var friends = [{
    > name: 'Anna',
    > books: ['Bible', 'Harry Potter'],
    > age: 21
    > }, {
    > name: 'Bob',
    > books: ['War and peace', 'Romeo and Juliet'],
    > age: 26
    > }, {
    > name: 'Alice',
    > books: ['The Lord of the Rings', 'The Shining'],
    > age: 18
    > }];
    >
    > // allbooks - list which will contain all friends' books +
    > // additional list contained in initialValue
    > var allbooks = friends.reduce(function(prev, curr) {
    > return [...prev, ...curr.books];
    > }, ['Alphabet']);
    >
    > // allbooks = [
    > // 'Alphabet', 'Bible', 'Harry Potter', 'War and peace',
    > // 'Romeo and Juliet', 'The Lord of the Rings',
    > // 'The Shining'
    > // ]
    >