面试题:JS数组对象去重在从小到大排序

<script type="text/javascript">
let arr = [
    { val: 1},
    { val: 2},
    { val: 5},
    { val: 4},
    { val: 3},
    { val: 5}
]

// 根据val排序(小到大)
arr.sort(function (a, b) {
    console.log(a.val - b.val)
    return a.val - b.val;
});
console.log(arr, '----arr')

// 定义去重方法(使用es6里面的reduce)
let deWeightArrayObj = (arr) => {
    let obj = {}
    arr = arr.reduce((newArr, next) =>{
        obj[next.val] ? '' : (obj[next.val] = true && newArr.push(next));
        return newArr
    }, []);
    return arr
}


console.log(deWeightArrayObj(arr))
</script>

 

reduce函数解释:

 

posted @ 2022-08-26 18:35  蜗牛snail  阅读(115)  评论(0编辑  收藏  举报
蜗牛前端 蜗牛文学