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" } ]