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]
网友评论