Detailed explanation of reduce() method and usage in JS

The reduce() method can do a lot of things. Reduce can do everything that loop traversal can do, such as array summation, array product, and counting elements in an array. The number of occurrences, array deduplication and so on.

The reduce() method executes a reduce function you provide (in turn) on each element in the array, summarizing its results into a single return value.

 1. Introduction to grammar

// arr.reduce(callback,[initialValue])

array.reduce((prev, cur, index, arr)=> {
    /***/
}, initialValue)

 reduce executes the callback function in sequence for each element in the array =4>, accepts four parameters: initial value initialValue (or the return value of the last callback function), current element value, current index, call reduce array.

Parameters: 

 Parameter 1: callback function (function that executes each value in the array, contains four parameters):

  •     prev required (the value returned by the last callback call, or the provided initial value (initialValue))
  •     Cur required (the element currently being processed in the array)
  •     index optional (the index of the current element in the array)
  •     arr Optional (the array on which reduce is called)

Parameter two: initialValue optional (indicates the initial value, as the first parameter of the first callback.)

        Provide the initial value, cur starts from the first item of the array, if< a i=4> does not provide an initial value, then cur starts executing from the second item, corresponding to the first prev is the value of the first item of the array 

2. Instance analysis of initialValue parameter

 Example 1:

  • The initial iteration value of the function is not set
<script>
    let arr = [1, 2, 3, 4, 5];
    let sum = arr.reduce(function (prev, cur, index, arr) {
        console.log(prev, cur, index);
        return prev + cur;
    });
    console.log('arr:', arr, 'sum:', sum);
</script>

operation result:

 Analysis: The function of reduce here is to sum the array. It can be seen here that the length of the array is 5, but the reduce function loops 4 times, and the function iterates < /span> is 1, which is the default value (the first item of the array). The index starts from 1. The value of the first prev is the array. The first value of prev is the value after each calculation. The initial value

Let’s look at example two:

  • Set the initial iteration value of the function
<script>
    let arr = [1, 2, 3, 4, 5];
    let sum = arr.reduce(function (prev, cur, index, arr) {
        console.log(prev, cur, index);
        return prev + cur;
    }, 5) //注意这里设置了初始值
    console.log("arr:", arr, "sum:", sum);
</script>

operation result:

 

 

Analysis: Here we add an initial iteration value, that is, let prev start calculation from 0 (summation with 0 as the initial value), index starts from 0, the array length is 5, the reduce function loops 5 times, and the result is also Initial value added.

in conclusion:

If no initialValue is provided, reduce will execute the callback method starting from index 1, skipping the first index.

If initialValue is provided, starts at index 0.

3. Things to note

1. reduce is a method that accumulates operations on an array. When using it, you need to the data of the accumulation operation. In this way, prev can obtain the result of the last execution, otherwise it is undefined;returnsreturnplus

2. When the reduce operation is performed on an empty array and no initial value is provided, reduce will report an error. The error message is as follows:

<script>
    // 空数组的情况
    let arr = [];
    let sum = arr.reduce(function (prev, cur, index, arr) {
        console.log(prev, cur, index);
        return prev + cur;
    })
//报错,"TypeError: Reduce of empty array with no initial value"
</script>

 But if we set the initial value, no error will be reported, as follows:

<script>
    // 空数组,但设置 初始值 的情况
    let arr = [];
    let sum = arr.reduce(function (prev, cur, index, arr) {
        console.log(prev, cur, index);
        return prev + cur;
    }, 0)
    console.log(arr, sum); // [] 0
</script>

4. Application of reduce

 (1) The simplest one is the commonly used array summation and product .

let arr = [1, 2, 3, 4];
let sum = arr.reduce((x,y)=>x+y)
let mul = arr.reduce((x,y)=>x*y)
console.log( sum ); //求和,10
console.log( mul ); //求乘积,24

 (2) Calculate the number of occurrences of each element in the array

<script>
    let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
    let nameNum = names.reduce((pre, cur) => {
        if (cur in pre) {
            pre[cur]++
        } else {
            pre[cur] = 1
        }
        return pre
    }, {})
    console.log(nameNum); //{Alice: 2, Bob: 1, Bruce: 1, Tiff: 1}
</script>

analyze:

1. Since sets the iteration initial value , the first value of pre is an empty Object, the name is Alice at this time, and then make a judgment and find that there is no Alice attribute in pre, so the attribute value corresponding to Alice is assigned to 1.
2. The same principle applies to the following items that are not repeated. If a repeated value is encountered, the attribute value will be increased by 1, so that the repeated elements can be calculated. times.

 (3) Array deduplication

<script>
    let arr = [1, 2, 3, 4, 4, 1]
    let newArr = arr.reduce((pre, cur) => {
        if (!pre.includes(cur)) {
            return pre.concat(cur)
        } else {
            return pre
        }
    }, [])
    console.log(newArr);// [1, 2, 3, 4]
</script>

 (4) Convert a two-dimensional array into a one-dimensional array

<script>
    let arr = [[0, 1], [2, 3], [4, 5]]
    let newArr = arr.reduce((pre, cur) => {
        return pre.concat(cur)
    }, [])
    console.log(newArr); // [0, 1, 2, 3, 4, 5]
</script>

(5) Convert multi-dimensional arrays into one-dimensional

<script>
    let arr = [[0, 1], [2, 3], [4, [5, 6, 7]]]
    const newArr = function (arr) {
        return arr.reduce((pre, cur) => pre.concat(Array.isArray(cur) ? newArr(cur) : cur), [])
    }
    console.log(newArr(arr)); //[0, 1, 2, 3, 4, 5, 6, 7]
</script>

(6) Sum of attributes in the object

<script>
    let result = [
        {
            subject: 'math',
            score: 10
        },
        {
            subject: 'chinese',
            score: 20
        },
        {
            subject: 'english',
            score: 30
        }
    ];

    var sum = result.reduce(function (prev, cur) {
        return cur.score + prev;
    }, 0);
    console.log(sum) //60
</script>

 (6), Classify Object by attributes

let person = [
    {
        name: 'xiaoming',
        age: 18
    },{
        name: 'xiaohong',
        age: 17
    },{
        name: 'xiaogang',
        age: 17
    }
];
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;
  }, {});
}
let groupedPerson = groupBy(person, 'age');
console.log(groupedPerson);

 operation result:


Summarize:

reduce() is a merging method of arrays. Like forEach(), map(), filter() and other iteration methods, each item of the array will be traversed. But< /span>reduce() can simultaneously operate on the results generated by traversing previous array items and the current traversed item, which is beyond the reach of other iteration methods.

Guess you like

Origin blog.csdn.net/weixin_48594833/article/details/128830644