美文网首页
由对象组成的数组去重方法

由对象组成的数组去重方法

作者: 双耳云 | 来源:发表于2019-10-18 09:44 被阅读0次

    1.定义数组对象:

    let list = [{
        id:1,
        date: '2016-05-02',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1518 弄'
      }, {
        id:2,
        date: '2016-05-04',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1517 弄'
      }, {
        id:3,
        date: '2016-05-01',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1519 弄'
      }, {
        id:4,
        date: '2016-05-03',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1516 弄'
      }
    ];
    

    2.使用数组的reduce()方法

    reduce()方法:接收一个函数作为累积器,数组中的每个值从左到右开始合并,最后返回一个值

    let hash = {};
    list = list.reduce((preVal, curVal) => {
      hash[curVal.id] ? '' : hash[curVal.id] = true && preVal.push(curVal);
      return preVal
    }, []);
    console.log('data', data)
    console.log('hash', hash)
    

    相关文章

      网友评论

          本文标题:由对象组成的数组去重方法

          本文链接:https://www.haomeiwen.com/subject/jjbhuctx.html