1.reduce 求数组中数值之和
/**
* 1. reduce 求和
*/
let arr = [1, 2, 3, 4, 5];
// let sum = arr.reduce(function (pre, cur, index) {
// console.log(pre, cur, index);
// return pre + cur;
// })
let sum = arr.reduce((x, y) => x + y)
console.log(sum); // 15
2.reduce 统计数组中相同项出现的次数,用对象方式表达出来
/**
* 2. reduce 统计数组中相同项出现的次数,用对象方式表达出来
* ["Booy","Jiexi","Tio","Kori","Jiexi"]
* {"Booy":1, "Jiexi":2, "Tio":1, "Kori":1}
*/
let names = ["Booy", "Jiexi", "Tio", "Kori", "Jiexi"];
let obj = names.reduce((pre, cur, curIndex) => {
if (cur in pre) {
pre[cur]++;
} else {
pre[cur] = 1;
}
return pre
}, {})
console.log(obj); //{Booy: 1, Jiexi: 2, Tio: 1, Kori: 1}
3.reduce 数组去重
/**
* 3. reduce 数组去重
*/
let num = [2, 5, 3, 6, 2, 3, 9, 3];
let newArr = num.reduce((pre, cur) => {
if (pre.includes(cur)) {
return pre;
} else {
return pre.concat(cur)
}
}, [])
console.log(newArr); //(5) [2, 5, 3, 6, 9]
4.reduce 将多维数组 转换为 一维数组
/**
* 4. reduce 将多维数组 转换为 一维数组
*/
// 4.1 二维数组 ----> 一维数组
let arr1 = [1, [2, 3], [4, 5, 6]];
let newArr1 = arr1.reduce((pre, cur) => {
return pre.concat(cur);
}, [])
console.log(newArr1); //(6) [1, 2, 3, 4, 5, 6]
// 4.2 多维数组 ----> 一维数组
let arr2 = [1, [2, [3, 4]], [5, [6, [7]]]];
let newArr2 = function (arr) {
return arr.reduce((pre, cur) => {
return pre.concat(Array.isArray(cur) ? newArr2(cur) : cur)
}, [])
}
console.log(newArr2(arr2)); //(7) [1, 2, 3, 4, 5, 6, 7]
5.reduce 将数组中的对象里的属性求和
/**
* 5. reduce 对象里的属性求和
*/
let result = [
{
subject: "math",
score: 10
},
{
subject: "chinese",
score: 20
},
{
subject: "english",
score: 30
}
]
let sum1 = result.reduce((pre, cur) => {
return pre + cur.score
}, 0)
console.log(sum1); //60