es6 reduce()的一些用法

// 计算数组中最大值
const arr = [1,2,3,4,5,6,7,8,9]
let max = arr.reduce((max, age) => {
    return max > age ? max : age
},0)
<!--console.log(max)-->

// 数组转哈希对象
const colorArray = [
    {
        id: 'fekokj',
        title: 'rad red',
        rating: 3
    },
    {
        id: 'amikom',
        title: 'big blue',
        rating: 2
    },
    {
        id: 'fdkm',
        title: 'grizzly gray',
        rating: 5
    },
    {
        id: 'mgiohnm',
        title: 'banana',
        rating: 1
    }
]

const hashObject = colorArray.reduce(
    (hash, {id, title, rating}) => {
        hash[id] = {title, rating}
        return hash
    }, 
    {}
)
<!--console.log(hashObject)-->

// 去重
const someArray = [1,1,2,2,3,3,4,4,'str','str',true,true,false]
const res = someArray.reduce(
    (distinct, item) => {
        return distinct.indexOf(item) > -1 ?
        distinct :
        [...distinct, item]
    },
    []
)
console.log(res)

 

posted @ 2022-10-28 11:30  追风不跟风  阅读(73)  评论(0)    收藏  举报