JavaScript native functions Array.prototype.reduce Practical usage and detailed explanation of essence

Posted by elToro on Sun, 21 Jun 2020 09:31:42 +0200

Reduce function is one of the array functions in JavaScript, which has powerful functions. But most of the blog's explanations of reduce function are comparison and basis.

Basic usage of reduce

Let's first look at the basic usage of reduce. Because the basic usage of reduce is explained in detail in MDN, we suggest you go to MDN directly

JavaScript | MDN | Array.prototype.reduce()
There are several typical examples

Example 1. 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) {
  return accumulator
}, [])


In fact, if you don't use Set, you can use filter at first. However, because filter can't get the result array of iteration, you need to use the array defined externally to implement filter, forEach and map, for example

var myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd'];
var resultArray = [];
myArray.forEach(item => {
    if(resultArray.indexOf(item) === -1){

Example 2. Use Promise iteratively

function runPromiseInSequence(arr, input) {
  return arr.reduce(
    (promiseChain, currentFunction) => promiseChain.then(currentFunction),

// 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

The feature of reduce is that the previous iteration results can be used in the iteration process

So we come to the first conclusion:

In the process of iteration, if the iteration results need to be used, reduce is suitable
On the contrary, if there is no need to use the iterative result during the iterative process, then Array.prototype Other functions on can be used for any logic.

Example 3: change the originArray array into a one-dimensional array

let originArray = [1,[2,3],[4,[5,6,[7,8],9],10,[11,12,[13,14],15],16],17];
function smoothArray(array){
    return array.reduce((resultArray, currentValue) => {
        let concatArray;
            concatArray = smoothArray(currentValue);
            concatArray = [currentValue];
        return resultArray.concat(concatArray);
    }, [])
// Results: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]

In this example, we recursively reduce the N-dimensional array originArray to a one-dimensional array.
Obviously, if you want to change originArray into a 0-dimensional array (0-dimensional array is a value), this method is also feasible. The way to become a 0-dimensional array (a value) can be accumulation, multiplication, subtraction and other methods. Here, what method is not important, what is important is what reduce has done and what is the essence of reduce.

What is the essence of reduce?

Abstractly, the caller of reduce must be an array, which is at least a one-dimensional array. The result is a value, which may be an array, an object, or a value in the basic JavaScript type.
What reduce does is:
Array = > a value
We and Array.prototype Compared with other functions on, map, forEach and filter must return an array; includes, find and findIndex must return a value; reduce does the process of "compressing" a high-dimensional thing into a value.
A friend who has read the three body must be impressed by the four-dimensional civilization described in the three body III and the two-dimensional plot of the solar system. The process of dimensionality reduction is almost inevitably accompanied by the loss of information. Reduce is no exception. When you change an array into a value through reduce, more or less, you must lose some information.

Finally, to summarize the essence of reduce:

Dimensionality reduction

Topics: Javascript P4 less