js数组reduce方法的详解
👀一起来瞅瞅reduce到底是怎么个事?
📕 reduce是数组的一个方法,它可以对数组进行迭代,通过回调函数对数组每一次迭代进行处理,从而获取到我们想要的结果。
1、reduce方法的参数如下
ok ,结合代码来看看上面总结的是否正确
list = [1, 2, 3, 4, 5]
const init = 0
list.reduce((pre, cur, index, arr) => {
console.log(pre, cur, index , arr)
return '我是返回给pre的值'
})
console.log('-------------分割线--------------')
list.reduce((pre, cur, index, arr) => {
console.log(pre, cur, index , arr)
return '我是返回给pre的值'
}, 0)
通过结果发现,第一次没有给初始值。pre将数组第一项当作默认值,cur从第二项开始所以只迭代了四次。每次迭代的返回值都传给了pre, index为当前迭代对象的下标 ,arr为原数组
|第二次传递了初始值,迭代也发生了相应的改变
👌: 看到这相信已经明白了reduce的参数以及作用, 下面使用reduce来解决一些问题吧!
1、使用reduce进行数组求和
list = [1, 2, 3, 4, 5]
let res = list.reduce((pre, cur)=>{
console.log('累计和:'+pre,'当前项:'+cur)
return pre+cur
})
console.log('结果: '+res)
2、🤣看注释需求(题目有点长)
/*
需求: 将以下数组type相同的项保留一个votes值最大的, 得到一个新数组
比如:
type为1的仅保留votes最大的100, type为2的仅保留votes最大的60...
*/
var list = [
{ type: 1, des: "aaaa", votes: 80 },
{ type: 2, des: "dddd", votes: 60 },
{ type: 3, des: "dddd", votes: 70 },
{ type: 1, des: "aaaa", votes: 50 },
{ type: 3, des: "dddd", votes: 80 },
{ type: 8, des: "dddd", votes: 80 },
{ type: 9, des: "dddd", votes: 20 },
{ type: 1, des: "aaaa", votes: 100 },
{ type: 3, des: "dddd", votes: 30 },
]
var newArr = list.reduce((pre, cur) => {
// 查找每次迭代返回的数组中有没有和本次type相同的项
let foundIndex = pre.findIndex(item => item.type === cur.type)
console.log(foundIndex)
if(foundIndex !== -1){
// 如果有就进行votes的比较
if(cur.votes > pre[foundIndex].votes){
// 若本次的大于pre中的则进行替换
pre[foundIndex] = cur
}
}else{
// 若本次没有与当前type相等的就push进数组并且返回
pre.push(cur)
}
return pre
}, []) //注意,这里的初始值可以为一个空数组哦
console.log(newArr)
🤷♂️reduce就到这里吧!