1、数组求和-reduce()方法最直接的用法就是对数组元素求和
let total = [34, 12, 143, 13, 76].reduce(
(previousValue, currentValue) => previousValue + currentValue,
0
);
console.log(total);
// 结果:278
2、扁平数组
const array = [[0, 1], [2, 3], [4, 5], [5, 6]];
const flattenedArray = array.reduce(
(previousValue, currentValue) => previousValue.concat(currentValue),
[]
);
console.log(flattenedArray);
// 结果:[0, 1, 2, 3, 4, 5, 5, 6]
3、统计数组元素出现次数
const colors = ['green', 'red', 'red', 'yellow', 'red', 'yellow', 'green', 'green'];
const colorMap = colors.reduce((previousValue, currentValue) => {
previousValue[currentValue] >= 1 ? previousValue[currentValue]++ : previousValue[currentValue] = 1;
return previousValue;
},
{}
);
console.log(colorMap);
结果
{green: 3, red: 3, yellow: 2}
4、反转字符串
const str = 'hello world';
[...str].reduce((a,v) => v + a); // 输出结果:'dlrow olleh'
5、数组去重
const arr = [1,2,6,5,9,5,1];
const dedupe = (acc, currentValue) => {
if (!acc.includes(currentValue)) {
acc.push(currentValue);
}
return acc;
};
const dedupedArr = arr.reduce(dedupe, []);
console.log(dedupedArr); // [1, 2, 6, 5, 9]
6、用set去重是比较好点的,性能更高,效率好的方法
const arr = [1,2,6,5,9,5,1];
let d = [...new Set(arr)];
console.log(d); // [1, 2, 6, 5, 9]