Reduce the JS () Detailed methods using arrays to reduce weight

 One ❀ lead

Learn a little JavaScript API array of students, there have been methods to reduce at least one side of the border, perhaps for the forEach too strong, or filter, find very useful, in the actual development start to finish I have not used the reduce method once. Coincidentally process today painted face questions, the questions encountered a problem, correlation analysis on the operation of the array was to reduce the use of methods, well I admit I looked a little confused, because I never had it in the eye , today gave a song of the time with each other, let us try to understand you, about reduce beginning of this article.

 About reduce II ❀

A complete reduce approach should be like this:

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

It consists of a callback function with an initial value, where the callback function takes four arguments, we first explain the meaning of initialValue callback form of participation:

1.initialValue [ɪnɪʃl] [væljuː] Initial value

represents initialValue reduce method of performing an initial value is an optional value.

2.accumulator [əkjuːmjəleɪtər] accumulator; accumulation by

As translation accumulator as it is the cumulative result of the reduce method executed several times , the initial value of the accumulator of two cases:

If initialValue provide an initial value, when the value of the first cycle of the accumulator is then initialValue , accumulator return to the previous value of the loop when the subsequent cycles.

Failure to provide initialValue, accumulator first cycle when the value of the first array arr [0], the subsequent cycle as the return value of the last cycle.

3.currentValue [kɜːrənt] [væljuː] current value

This should not be difficult to understand, an array of loop current value of the process. The initial value currentValue also affected initialValue of:

If the initial value initialValue provided, the first value of the first cycle currentValue array arr [0], subsequent incremental changes with changes in the index.

Failure to provide the initialValue, since the first cycle arr [0] become the accumulator value, the currentValue only from arr [1] start, subsequent changes with the index is incremented.

4.currentIndex

Loop index array, currentValue with the current process value currentIndex change synchronously.

5.array

Currently it is circulated array.

Said a little confused? It does not matter, we have to understand step by step through an example, a deeper impression of these parameters. Look at the first example:

let arr = ['e', 'l', 'l', 'o'];
arr.reduce((accumulator, currentValue, currentIndex, array) => {
    console.log(accumulator, currentValue, currentIndex, array);
});

Our printing out four parameters, Huh? Why accumulator first cycle is e, how the subsequent cycles are undefined?

Said earlier, since the reduce method does not provide an initial value , the first initial value as the reduce method of the first cycle of the array , no subsequent cycles since the return operation, leading to get the last return accumulator value, so that undefined up.

We add return behind the operation console, look at:

return accumulator+currentValue;

This value is not there yet, so reduce the use of the method must remember, is a method of operation due reduce cumulative array, in use got to remember to add return return you want to accumulate data manipulation.

That is not right ah, I obviously have an array of four, according to how the output of view reduce method is performed only three times?

This is because we do not provide an initial value initialValue, the method will lead to reduce the array as the first initial value, so the cycle for the first time from the start of the second item in the array , we try to add a default value to reduce:

let arr = ['e', 'l', 'l', 'o'];
arr.reduce((accumulator, currentValue, currentIndex, array) => {
    console.log(accumulator, currentValue, currentIndex, array);
    return accumulator+currentValue;
},'h');

With the default values ​​can be seen, the array from the first cycle is zero-based index, a full account of the implementation of four times.

Nor ah, accumulator cycle is not accumulated value it, how the finished display is hell, o how not added to the list? This is not because I wrote it on the console front return yet (I mean it), has finished the last one out of the loop, reduce method returns the final results of the implementation, we use a variable to hold try, like this:

let arr = ['e', 'l', 'l', 'o'];
let result = arr.reduce((accumulator, currentValue, currentIndex, array) => {
    return accumulator+currentValue;
},'h');
console.log(result);//hello

看,这不就是一个完整的单词 hello了;

其实对于reduce让人疑惑的无非就是initialValue与accumulator,currentValue的关系,这里我们做个小总结:

如果reduce有提供初始值,则循环从索引0开始,此时accumulator就是initialValue,currentValue值就是arr[0];如果reduce未提供初始值,则arr[0]作为初始值赋予给accumulator,循环从索引1开始,currentValue值就是arr[1]了;

 叁 ❀ reduce作用

那么到这里我们详细介绍了reduce方法的参数与执行规则,了解了这些,我们可以用reduce方法做些什么呢?

1.数组求和

reduce方法本意就是用来记录循环的累积结果,用于数组求和是最合适不过了。比如我们要求数组 [1,2,3,4] 的元素之和,用forEach你得这样写:

let total = 0;
[1, 2, 3, 4].forEach(item => total += item);
console.log(total); //10

但通过reduce方法就简单的多,我们可以这么写:

let total = [1, 2, 3, 4].reduce((accumulator, current) => accumulator += current); // 10

假设我们希望求数字90与数组 [ 1,2,3,4] 元素的和呢,那就这么写:

let total = [1, 2, 3, 4].reduce((accumulator, current) => accumulator += current, 90); // 100

2.数组去重

比如我们要将数组 [1,2,2,4,null,null] 去除掉重复项,用filter可以这样做:

let arr = [1, 2, 2, 4, null, null].filter((item, index, arr) => arr.indexOf(item) === index); // [1,2,4,null]

当然单说实现使用 new Set 更简单:

let arr = [...new Set([1, 2, 2, 4, null, null])]; // [1,2,4,null]

现在我们知道了reduce方法,其实也可以通过reduce去重,像这样:

let arr = [1, 2, 2, 4, null, null].reduce((accumulator, current) => {
    return accumulator.includes(current) ? accumulator : accumulator.concat(current);
}, []);

3.数组降维

比如我们要将二维数组 [[1,2],[3,4],[5,6]] 降维成一维数组,最简单的做法是通过flat方法,像这样:

let arr = [[1,2],[3,4],[5,6]].flat();//[1, 2, 3, 4, 5, 6]

通过reduce也挺简单,我们可以结合concat方法,像这样:

let arr = [[1,2],[3,4],[5,6]].reduce((accumulator, current)=>accumulator.concat(current),[]);//[1, 2, 3, 4, 5, 6]

那如果是个多维数组呢,reduce可以这样做:

let arr = [0,[1],[2, 3],[4, [5, 6, 7]]];

let dimensionReduction = function (arr) {
    return arr.reduce((accumulator, current) => {
        return accumulator.concat(
            Array.isArray(current) ? 
            dimensionReduction(current) : 
            current
            );
    }, []);
}
dimensionReduction(arr); //[0, 1, 2, 3, 4, 5, 6, 7]

相对而言,多维数组降维flat会更简单,当然flat存在兼容问题:

let arr = [0,[1],[2, 3],[4, [5, 6, 7]]].flat(Infinity);// [0, 1, 2, 3, 4, 5, 6, 7]

 肆 ❀ 使用注意

在使用reduce方法有一点需要注意,若有初始值但数组为空,或无初始值但数组只有一项时,reduce方法都不会执行。

[].reduce(() => console.log(1), 1); //不会执行
[1].reduce(() => console.log(1)); //不执行

若数组为空且没有初始值,reduce方法报错。

[].reduce(() => console.log(1)); //报错

所以如果没有初始值,你至少得保证数组有2项才能执行;如果给了初始值,你至少得保证数组有一项才能执行。

[1, 2].reduce(() => console.log(1)); //1
[1].reduce(() => console.log(1), 1); //1

 伍 ❀ 总

通过文本,我们知道了reduce是一个进行累积操作的方法,当我们提供初始值时,循环从0开始,如果不提供,则循环从索引1开始。

我们知道了reduce还有那么点傲娇,如果数组为空且不提供初始值时reduce会报错,如果想reduce执行,你的数组最低标准应该有一项,同时提供默认值(或数组有两项无初始值)。

那么到这里,关于reduce方法参数与基本用法就全部介绍完毕了。

 参考

JS数组reduce()方法详解及高级技巧

MDN

Guess you like

Origin www.cnblogs.com/echolun/p/11929564.html