javaScript--Analysis of Reduced Array Method

Keywords: Javascript Firefox IE

Overview: Array in javaScript contains not only reduce methods, but also foreach,map,filter and so on. Here we mainly introduce reduce methods.

Reduc () accumulates data from left to right until the end is a value (that is, the final result), which sounds abstract. The accumulated attention can be either data or string editing.

1. Grammar:

arr.reduce(callback, [initialValue])

Parametric analysis:

arr: An array that represents the accumulation

callback: callback function (that is, how do you deal with arrays)

There are four parameters in the callback function:

accumulator: The cumulative result, the result of the last callback, or the initial value (if provided)

CurrtValue: Current value, the next value to be processed

CurrtIndex: An index representing the current value (starting from 0), if an initial value provides an index of 1

array: A cumulative group is required

Initial Value: If an initial value (optional parameter) is provided as the first parameter (accumulator) of the first callback, the first element of the array is taken if it is not provided, and if it is neither an initialization parameter nor an empty array, an exception is thrown.

2. Description:

If the first callback passes in the initial value, accumulator is the initial value, and currentValue is the first value of the array. If no initial value is provided, accumulator will take the first value of the array, and currentValue, of course, is the second value.

If the array is empty and there is no initialization value, a TypeError (type exception) will be thrown. If the array is empty and the initial value is passed in or not, the array has only one element. The callback function will not be called and the value of the element or the initial value will be returned directly.


//These are arrow functions.
var maxCallback = ( acc, cur ) => Math.max( acc.x, cur.x );
var maxCallback2 = ( max, cur ) => Math.max( max, cur );

// Calling reduce method does not pass in the initial value
[ { x: 22 }, { x: 42 } ].reduce( maxCallback ); // The result was 42.
[ { x: 22 }            ].reduce( maxCallback ); // The result is: {x: 22}
[                      ].reduce( maxCallback ); // Throw an exception TypeError

// The array map traverses to the number corresponding to x (one step in advance) and calls back.
[ { x: 22 }, { x: 42 } ].map( el => el.x )
                        .reduce( maxCallback2, -Infinity );

3. Reduc () Specific working process

Here's an example
[0, 1, 2, 3, 4].reduce(
  function (
    accumulator,
    currentValue,
    currentIndex,
        array
 ) { return accumulator + currentValue; });
Specific callbacks are shown in the following table (no initial values are passed in)
Callback Cumulative value Current value Current Index array Return value
For the first time 0 1 1 [0,1,2,3,4]
1
The second time 1 2 2 [0,1,2,3,4]
3
Third time 3 3 3 [0,1,2,3,4]
6
Fourth time 6 4 4 [0,1,2,3,4]
10

It can also be represented by an arrow function:
[0,1,2,3,4].reduce((prev, curr)=> prev + curr );
For the case of incoming initialization values
[0, 1, 2, 3, 4].reduce(
  (accumulator, currentValue, currentIndex, array) => {
    return accumulator + currentValue;
  },
  10
);
Input initial value is 10, return 20
Callback Cumulative value Current value Current Index array Return value
For the first time 10 0 0 [0,1,2,3,4] 10
The second time 10 1 1 [0,1,2,3,4]
11
Third time 11 2 2 [0,1,2,3,4]
13
Fourth time 13 3 3 [0,1,2,3,4]
16
Fifth time 16 4 4 [0,1,2,3,4]
20

4. Start with examples

a. Accumulation
var sum = [0, 1, 2, 3].reduce(function (a, b) {
  return a + b;
}, 0);
// sum is 6
You can use arrow functions
var total = [ 0, 1, 2, 3 ].reduce(
  ( acc, cur ) => acc + cur,
  0
);
b. Stitching strings
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
  function(a, b) {
    return a.concat(b);
  },
  []
);
// The results of stitching are [0, 1, 2, 3, 4, 5]
Available arrow function
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
  ( acc, cur ) => acc.concat(cur),
  []
);
c. Field Counting

var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
var countedNames = names.reduce(function (allNames, name) { 
  if (name in allNames) {
    //Corresponding name field cumulative 1
    allNames[name]++;
  }
  else {
    //Create a new name field number of 1
    allNames[name] = 1;
  }
  return allNames;
}, {});
console.log(countedNames);
// The countedNames result is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
d. Continue to expand
// Friends-y An Array Object
// The field books in the object represents all 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
}];

// List all your friends'favorite books + books with initial values
var allbooks = friends.reduce(function(prev, curr) {
  //Refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters for details.
  return [...prev, ...curr.books];
}, ['Alphabet']);
//The results are as follows:
// allbooks = [
//   'Alphabet', 'Bible', 'Harry Potter', 'War and peace', 
//   'Romeo and Juliet', 'The Lord of the Rings',
//   'The Shining'
// ]

5. Minimum version of browser compatibility

Chrome support, firefox 3.0(1.9),
  IE 9 , Opera 10.5 , Safari 4.0
Summary:
Reduc () function is still very powerful, the main cumulative operation, accumulation or splicing, etc., as long as the cumulative operation can be considered with reduce.
This article refers to official documents:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce?v=control


   


        
    

Posted by eric_e on Tue, 25 Jun 2019 17:33:20 -0700