一、介绍基本用法
二、使用场景
聚合,包括求和、求平均值、出现的次数等
1. 数组求和、求积、计算数组对象中某属性的总和
const numbers = [1, 2, 3, 4, 5];
let res = numbers.reduce((pre, cur, index) => {
pre += cur;
if (index === numbers.length - 1) {
return pre / numbers.length;
} else {
return pre;
}
}, 0);
console.log(res);
var data = [
{
subject: "math",
score: 10,
},
{
subject: "chinese",
score: 20,
},
{
subject: "english",
score: 30,
},
];
let res = data.reduce((pre, cur) => {
return pre + cur.score;
}, 0);
console.log(res);
2. 数组去重
let data = [1, 2, 3, 4, 1, 2, 3, 5, 6, 7, 8];
let res = data.reduce((pre, cur) => {
if (pre.includes(cur)) {
return pre;
} else {
pre.push(cur);
return pre;
}
}, []);
console.log(res);
3. 统计元素出现的次数
// 输出: { Alice: 2, Bob: 1, Tiff: 1, Bruce: 1 }
const names = ["Alice", "Bob", "Tiff", "Bruce", "Alice"];
let res = names.reduce((pre, cur) => {
if (pre[cur]) {
pre[cur]++;
} else {
pre[cur] = 1;
}
return pre;
}, {});
console.log(res);
4. 数组扁平化
const data = [1, 2, [3, 4, [5, 6, 7]], 8, 9, [10, 11]];
const myFlat = (arr) => {
return arr.reduce((pre, cur) => {
return pre.contact(Array.isArray(cur) ? myFlat(cur) : cur);
}, []);
};
console.log(res);
5. 分组
const people = [
{ name: "Alice", age: 21 },
{ name: "Max", age: 20 },
{ name: "Jane", age: 20 },
];
let res = people.reduce((pre, cur) => {
if (!pre[cur.age]) {
pre[cur.age] = [];
}
pre[cur.age].push(cur);
return pre;
}, {});
console.log(res);