reduce()函数用法简单分析

菜鸟教程-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 }
}*/

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。