About the reduce() method in JavaScript

1, What is reduce()?

 

The reduce() method performs an ascending reducer function on each element in the array, and summarizes the result into a single return value

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// output: 15

 

 

2, Parameters of reduce method in array

 

1. First parameter: reducer function

Among them, the reducer function has four parameters:

  1. Accumulator (acc)
  2. Current Value (cur)
  3. Current Index (idx)
  4. Source Array (src)

 

2. Second parameter (optional): initialValue

Represents the initial value passed to the function

// The case of not passing the second parameter
var numbers = [1, 2, 3, 4]

function myFunction(item) {
    let result = numbers.reduce(function (total, currentValue, currentIndex, arr) {
        console.log(total, currentValue, currentIndex, arr)
        return total + currentValue
    })
    return result
}

myFunction(numbers)

Output:

You can see that if the second parameter initialValue is not passed, the first execution of the function returns the first element in the array as the total parameter. Three times in total


Here's how the second parameter is passed:

// The case of not passing the second parameter
var numbers = [1, 2, 3, 4]

function myFunction(item) {
    let result = numbers.reduce(function (total, currentValue, currentIndex, arr) {
        console.log(total, currentValue, currentIndex, arr)
        return total + currentValue
    }, 10)
    return result
}

myFunction(numbers)

Output:

If the second parameter initialValue is passed, the value of total is the passed parameter value at the first execution, and then the elements in the array are traversed in turn. Execute 4 times

Summary: if the second parameter initialValue is not passed, the function starts from the second value of the array, and the first value is the return value of the first execution. If the second parameter initialValue is passed, the function starts from the first value of the array, and the parameter initialValue is the return value of the first execution

 

 

3, Application scenario

 

1. Sum of all values in the array

var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
  return accumulator + currentValue;
}, 0);
// And 6

 

2. Accumulate values in an array of objects

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

 

3. Convert 2D array to 1D

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

 

4. Count the number of occurrences of each element in the array

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 }

 

5, Array de duplication

var myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd'];
var myOrderedArray = myArray.reduce(function (accumulator, currentValue) {
  if (accumulator.indexOf(currentValue) === -1) {
    accumulator.push(currentValue);
  }
  return accumulator
}, [])

console.log(myOrderedArray);
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]

Tags: Javascript

Posted on Mon, 16 Mar 2020 08:06:21 -0400 by arpowers