reduce()函数用法简单分析

2020-03-15  本文已影响0人  小恐龙yaya

菜鸟教程-reduce直通车
JS函数在线编辑直通车

用法

reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。

reduce() 可以作为一个高阶函数,用于函数的 compose。

注意: reduce() 对于空数组是不会执行回调函数的。

方法一:数组去重

const  colors=["red","red","green","blue"]
const distinctColors=colors.reduce(
    (distince,color)=>(distince.indexOf(color)!==-1)?distince:[...distince,color],[]
)
console.log(distinctColors)
// [ 'red', 'green', 'blue' ]

方法二:数取出数组中最大值

const ages=[21,98,34,48,31,36,31,34]
const maxAge=ages.reduce((max,age)=>(
    max>age?max:age
),0)
console.log("maxAge",maxAge)
// maxAge 98

方法三:将数组转化为对象

const users=[{id:1,title:'第一个名字',age:12}, {id:2,title:'第二个名字',age:19}, {id:3,title:'第三个名字',age:89}]
const objS=users.reduce((user,{id,title,age})=>{
    user[id]={title,age}
    return user
},{})
console.log(objS)
/*{
 '1': { title: '第一个名字', age: 12 },
 '2': { title: '第二个名字', age: 19 },
 '3': { title: '第三个名字', age: 89 }
}*/

以上为个人学习到的部分用法,学习过程中会进行补充。

上一篇 下一篇

猜你喜欢

热点阅读