小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
数组求和
我们平常是使用的方法是
const array = [1, 2, 3, 4, 3, 5, 7, 9 , 4];
let sum = 0;
array.forEach((item) => sum += item);
console.log(sum);
//求得的值为38
使用reduce进行累加求和
const array = [1, 2, 3, 4, 3, 5, 7, 9 , 4];
const res = array.reduce(((accumulator, currentValue, currentIndex, array) => {
return accumulator + currentValue;
}), 0);
// 第一个参数accumulator的作用:累计器,函数的返回值分配给累计器,该返回值在数组的每个迭代中被记住,并最后成为最终的单个结果值。
console.log(res);
//求得的值为38
数组扁平化
使用reduce进行扁平化数组
const arrayList = [[1, 2], [3, 4], [5, 6]];
const newArrayList = arrayList.reduce((accumulator, currentValue) => {
return accumulator.concat(currentValue);
});
console.log(newArrayList);
//求出的值为 [1, 2, 3, 4, 5, 6]
使用forEach扁平化数组
const arrayList = [[1, 2], [3, 4], [5, 6]];
let newArrayList = [];
arrayList.forEach((item) => newArrayList = newArrayList.concat(item));
console.log(newArrayList);
数组对象去重
使用reduce进行数组对象去重
const arrayObject = [
{"all": 1},
{"all": 2},
{"all": 3},
{"all": 4},
{"all": 1}
];
let obj = {};
const list = arrayObject.reduce((item, next) => {
if (!obj[next.all]) {
obj[next.all] = item.push(next);
}
return item;
}, []);
console.log(list);
//结果[
// {"all": 1},
// {"all": 2},
// {"all": 3},
// {"all": 4}
// ]
使用forEach进行数组对象去重
const arrayObject = [{"all": 1}, {"all": 2}, {"all": 3}, {"all": 4}, {"all": 1}];
let array = [];
let newArrayObject = [];
arrayObject.forEach(((item) => {
if (!array.includes(item["all"])) {
array.push(item["all"]);
newArrayObject.push(item);
}
}));
console.log(newArrayObject);
//结果[
// {"all": 1},
// {"all": 2},
// {"all": 3},
// {"all": 4}
// ]