js去除数组对象中的重复对象
1、根据数组对象中的id作比较,id相同的去掉。var arr = [{DocESOPTerminalId: "632cffab-4d49-45da-9ef7-af263914b6f9",LocationName: "测试列",FactoryId: "9c895538-6cf0-49a9-aca0-89531936118e",WorkShopId: "1b29ff90...
·
1、根据数组对象中的id作比较,id相同的去掉。这种方法只会保留 id 第一个出现的数组
第一种:
var arr = [
{id: 1, name: 'sli', year: 2012},
{id: 2, name: 'ap', year: 2015},
{id: 1, name: 'alslion', year: 2012},
{id: 3, name: 'pose', year: 2012},
]
//删除arr中的重复对象
var newArr= [];
var arrId = [];
for(var item of arr){
if(arrId.indexOf(item['id']) == -1){
arrId.push(item['id']);
newArr.push(item);
}
}
console.log(arrId,newArr);
结果如下:
第二种:reduce()
var arr = [
{name:'uzi',color:'blue'},
{name:'pdd',color:'white'},
{name:'mlxg',color:'orange'},
{name:'uzi',color:'red'},
]
let hash = {};
var newArr = arr.reduce((item, next) => {
hash[next.name] ? '' : hash[next.name] = true && item.push(next);
return item
}, []);
console.log(newArr);
结果如下:
第三种:
let arr = [
{name:'黎明',id:21111},
{name:'王小二',id:1111},
{name:'大小二',id:3222}
]
arr.splice(arr.findIndex(item => item.id === 3222), 1);
结果如下:
2、数组对象完全相同的去除
第一种:
function delObj(obj) {
var uniques = [];
var stringify = {};
for (var i = 0; i < obj.length; i++) {
var keys = Object.keys(obj[i]);
keys.sort(function(a, b) {
return (Number(a) - Number(b));
});
var str = '';
for (var j = 0; j < keys.length; j++) {
str += JSON.stringify(keys[j]);
str += JSON.stringify(obj[i][keys[j]]);
}
if (!stringify.hasOwnProperty(str)) {
uniques.push(obj[i]);
stringify[str] = true;
}
}
uniques = uniques;
return uniques;
}
var arr = [
{name:'uzi',color:'blue'},
{name:'pdd',color:'white'},
{name:'mlxg',color:'orange'},
{name:'uzi',color:'blue'},
]
console.log('arr:',delObj(arr))
var arr1 = [
{name:'uzi',color:'blue'},
{name:'pdd',color:'white'},
{name:'mlxg',color:'orange'},
{name:'uzi',color:'red'},
]
console.log('arr1:',delObj(arr1))
结果如下图所示:
第二种:引用Lodash
Lodash官网: https://www.lodashjs.com/docs/latest#_uniqwitharray-comparator
用法:_.uniqWith(array, [comparator])
例子
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.uniqWith(objects, _.isEqual);
// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
更多推荐
已为社区贡献1条内容
所有评论(0)