定义:对数组中的每个元素执行一个自定义的累计器操作,将其结果汇总为单个返回值。
array.reduce((pre, cur, index, array) => {}, initValue)
callback
:回调函数(必选)initValue
:初始值(可选)pre
:它是上一次调用回调时返回的累积值,或initialValue(必选)cur
:当前元素(必选)index
:当前元素的索引。如果提供了initialValue,则起始索引号为0,否则从索引1起始(可选)array
:调用reduce()的数组(可选)1.求和累乘
// 求和
const arr = [
{ name: '张三', score: 78 },
{ name: '李四', score: 92 },
{ name: '王五', score: 80 },
]
const sum = arr.reduce((pre, cur) => pre + cur.score, 0)
console.log(sum) // 250
// 累乘
const arr = [1, 2, 3, 4, 5]
const result = arr.reduce((pre, cur) => pre * cur, 1)
console.log(result) // 120
2.数组去重
const arr = [
{ name: '孙悟空', id: 1 },
{ name: '猪八戒', id: 2 },
{ name: '孙悟空', id: 1 },
{ name: '猪八戒', id: 2 },
{ name: '孙悟空', id: 1 },
{ name: '唐僧', id: 3 },
]
const result = arr.reduce((pre, cur) => {
const target = pre.find(c => c.id === cur.id)
if (!target) {
pre.push(cur)
}
return pre
}, [])
console.log(result) // [{ name: '孙悟空', id: 1 }, { name: '猪八戒', id: 2 }, { name: '唐僧', id: 3 }]
3.数组转对象
const arr = [
{ name: '诸葛亮', skill: '雷霆万钧' },
{ name: '百里守约', skill: '静谧之眼' },
{ name: '李白', skill: '万剑归宗' }
]
const result = arr.reduce((pre, cur) => {
pre[cur.name] = cur.skill
return pre
}, {})
console.log(result) // {'诸葛亮': '雷霆万钧', '百里守约': '静谧之眼', '李白': '万剑归宗'}
4.数组扁平化
const arr = [[[[1, 2, 3,], 4, 5], 6, 7, 8], 9, [10, 11, [[12]]]]
function flat(arr) {
return arr.reduce((pre,cur)=>{
return pre.concat(Array.isArray(cur) ? flat(cur) : cur)
},[])
}
const result = flat(arr)
console.log(result) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
5.分组
const arr = [
{ name: '孙悟空', id: 1 },
{ name: '猪八戒', id: 2 },
{ name: '孙悟空', id: 1 },
{ name: '猪八戒', id: 2 },
{ name: '孙悟空', id: 1 },
{ name: '唐僧', id: 3 },
]
const result = arr.reduce((pre, cur) => {
if (!pre[cur.name]) {
pre[cur.name] = []
}
pre[cur.name].push(cur)
return pre
}, {})
console.log(result) // {'孙悟空': Array[3], '猪八戒': Array[2], '唐僧': Array[1]}
6.数组成员个数统计
const arr = [
{ name: '孙悟空', id: 1 },
{ name: '猪八戒', id: 2 },
{ name: '孙悟空', id: 1 },
{ name: '猪八戒', id: 2 },
{ name: '孙悟空', id: 1 },
{ name: '唐僧', id: 3 },
]
const result = arr.reduce((pre, cur) => {
if (!pre[cur.name]) {
pre[cur.name] = 1
} else {
pre[cur.name] ++
}
return pre
}, {})
console.log(result) // {唐僧: 1, 孙悟空: 3, 猪八戒: 2}