js对单个数组集合元素进行去重

有时候我们需要对数据集合进行去重处理,提供一个方法:

function uni(arr) {
  let newArr = [];
  let obj = {};
  for (var i = 0; i < arr.length; i++) {
    if (!obj[arr[i].id]) {
      newArr.push(arr[i]);
      obj[arr[i].id] = true;
    }
  }
  console.log(newArr)
}

 测试:

var arr = [{
    id: 1,
    name: "zhangsan"
  },
  {
    id: 1,
    name: "lisi"
  },
  {
    id: 2,
    name: "wangwu"
  },
  {
    id: 2,
    name: "jack"
  },
  {
    id: 3,
    name: "susan"
  },
  {
    id: 3,
    name: "arek"
  },
]
uni(arr)

结果:

[
    {
        "id":1,
        "name":"zhangsan"
    },
    {
        "id":2,
        "name":"wangwu"
    },
    {
        "id":3,
        "name":"susan"
    }
]

 

posted @ 2021-02-01 11:03  wjs0509  阅读(428)  评论(0编辑  收藏  举报