Re-learn Array.reduce()

Recently, in the process of chopping language packages in the project, I found that a lot of repetitive work had been done, and then my colleagues pointed out the method of reducing, as if opening the door to a new world. So I relearned the use of reduce. Record it on your blog.

Tip: Try to simplify the article, but feel that there are many details about this function. So the impression might be that the blogger is a bb geek.  

Test:

If you can understand the principles of the following functions, you will not need to read this article at all.

// Version 1
[...new Array(100).values()].map((item, index) => index + 2).reduce((a, b) => `${a} MINE_${b}: "", \n`, 'MINE_1: "",');

// Another way of writing
[...new Array(100).toString().split(',').keys()].reduce((a, b) => `${a} MINE_${b}: "", \n`,'');

Definition

array.reduce( function(accumulator,  currentValue,  currentIndex,  array), initialValue ); 

accumulator: The value returned by the last call callback, or the initial value provided

CurrtValue: Elements being processed in an array

CurrtIndex: Index of elements being processed in the data, starting from 0 if initial Value is provided; otherwise starting from 1. [Optional]

Array: An array that calls reduce [optional]

initialValue: optional, whose value is used for the first parameter that callback is called for the first time. If no initial value is set, the first element in the array is taken as the initial value. [Optional] Note here that if you use []. reduce method on an empty array, you will report an error. See the following examples for reasons.

The return value of array.reduce is the result of the function's cumulative processing.

// Explain definitions in code
let demo = [ 333, 222, 111 ];

//No initial Value is defined
demo.reduce((acc, curVal) => { console.log(acc) })  
// Output: 333, undefined, undefined 

//Define initialValue 1
demo.reduce((acc, curVal) => { console.log(acc)}, 1)
// Output: 1, undefined, undefined 

//Empty arrays do not define initial Value
[].reduce((a,b) => console.log(a))
// Output: Uncaught TypeError: Reduce of empty array with no initial value
// Because no initial value is defined, a defaults to the first value of the array, while an empty array, the first value is undefined, so an error is reported.

/* Description: When the callback function is first executed, accumulator and current Value are selected in two cases: if initial Value is provided when reduce(), accumulator is taken as initial Value, current Value is taken as the first value in the array; if initialValue is not provided, accumulator takes the first value in the array. CurrtValue takes the second value in the array. There is undefined in the output because acc returns the result of the last function, but here our function is printed only, and there is no return value, so it is undefined. */

2. It can do something conveniently.

Array summation

Converting arrays into objects, calculating the number of occurrences of each element in an array, and classifying arrays by attributes

Run promise in sequence

2.1 Summation of Arrays

let demo = [ { x: 1}, { x: 2 }, { x: 3} ],

demo.reduce((arr,val) => { return arr + val.x }, 0); 

// return: 6

2.2 Array to Object

let demo = [
  {
    id: 1,
    username: 'john',
    sex: 1,
    email: 'john@163.com'
  },
  {
    id: 2,
    username: 'jerry',
    sex: 1,
    email: 'jerry@163.com'
  },
  {
    id: 3,
    username: 'nancy',
    sex: 0,
    email: ''
  }
];

demo.reduce( (acc,val) => { return {...acc, [val.username]: val} } , {} )

2.3 Perform promise in sequence

/**
 * Examples of direct copying of official websites
 * Runs promises from array of functions that can return promises
 * in chained manner
 *
 * @param {array} arr - promise arr
 * @return {Object} promise object
 */
function runPromiseInSequence(arr, input) {
  return arr.reduce(
    (promiseChain, currentFunction) => promiseChain.then(currentFunction),
    Promise.resolve(input)
  );
}

// promise function 1
function p1(a) {
  return new Promise((resolve, reject) => {
    resolve(a * 5);
  });
}

// promise function 2
function p2(a) {
  return new Promise((resolve, reject) => {
    resolve(a * 2);
  });
}

// function 3  - will be wrapped in a resolved promise by .then()
function f3(a) {
 return a * 3;
}

// promise function 4
function p4(a) {
  return new Promise((resolve, reject) => {
    resolve(a * 4);
  });
}

const promiseArr = [p1, p2, f3, p4];
runPromiseInSequence(promiseArr, 10)
  .then(console.log);   // 1200

2.4 Array Reduplication

reduce can do that, of course, but I prefer the following approach

let demo = [ 1, 1, 2, 3];

//One line completes array de-duplication and ascending sorting
[...new Set(demo)].sort();

Reference link:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

https://www.jianshu.com/p/b415e46b4c8a

Keywords: P4 Javascript

Added by nuttycoder on Tue, 27 Aug 2019 13:19:41 +0300