首页 > 其他 > 详细

(flag)每日三道面试题(4.25)

时间:2020-04-26 00:23:37      阅读:50      评论:0      收藏:0      [点我收藏+]

1.数组如何去重

使用reduce方法累加
reduce使用方法小总结

arr.reduce(callback,初始值)
回调中接收四个参数
//previousValue 初始值/返回值
//currentValue 当前处理的值
//index 索引值
//array数组
arr.reduce((previousValue,currentValue,index,array)=>{
//如果没有return 返回值 previousValue则是underfined
    
}

去重过程:

    const responseList = [
        { id: 1, a: 1 },
        { id: 2, a: 2 },
        { id: 3, a: 3 },
        { id: 1, a: 4 },
    ]
const result=responseList.reduce((acc,cur)=>{
//初始值为空数组来存放每个对象id值
//将每个对象映射成对象的id值对比
const ids=acc.map(item=>item.id);
//如果上个返回数组存在当前id值则返回原值,如果不存在将改项id加入
return ids.includes(cur.id)?acc:[...acc,cur];
},[])
console.log(result)
let result = responseList.reduce((acc, cur) => {
        const ids = acc.map(item => item.id);
        return ids.includes(cur.id) ? acc : [...acc, cur];
    }, [])
    console.log(result)  
 const responseList = [
        { id: 1, a: 1 },
        { id: 2, a: 2 },
        { id: 3, a: 3 },
        { id: 1, a: 4 },
        { id: 3, a: 4 },
        { id: 9, a: 4 },
        { id: 10, a: 4 },
    ]
    let result = responseList.reduce((acc, cur) => {
        const ids = acc.map(item => item.id)//1 (item.id)
        return ids.indexOf(cur.id)===-1 ?  [...acc, cur]:acc //2 (ids.indexOf(cur.id)===-1)
    }, [])
    console.log(result)

(flag)每日三道面试题(4.25)

原文:https://www.cnblogs.com/halfsoul/p/12775913.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!