先模拟一条数据
let arrays = [
{"id": 1, "name": "李四1"},
{"id": 2, "name": "李四"},
{"id": 2, "name": "李四"},
{"id": 1, "name": "李四1"},
{"id": 5, "name": "李四5"}
];
方法一:根据某一个属性是否重复
let obj = {};
arrays = arrays.reduce((item, next) => {
obj[next.id] ? '' : obj[next.id] = true && item.push(next);
return item;
}, []);
console.log(arrays);
方法二:借助于 for 循环实现某个属性的去重
let result = [];
let obj = {};
for(let i = 0; i < arrays.length; i++){
if(!obj[arrays[i].id]){
result.push(arrays[i]);
obj[arrays[i].id] = true;
}
}
console.log(result);
方法三:借助于 for 实现所有属性值相同的情况下去重
let result = [];
let obj = [];
let str;
for(let i = 0; i < arrays.length; i++){
str = JSON.stringify(arrays[i]);
if(obj.indexOf(str) == -1){
result.push(arrays[i]);
obj.push(str);
}
}
console.log(result)
方法四:对象的所有属性相同才能认为相同
let obj = [];
let str;
arrays = arrays.reduce((item, next) => {
str = JSON.stringify(next);
obj.indexOf(str) == -1 ? item.push(next) && obj.push(str) : '';
return item;
}, []);
console.log(arrays)
二维数组去重
对象的所有属性相同才能认为相同
let arrays = [
["id1", "name李四1"],
["id2", "name李四1"],
["id2", "name李四"],
["id1", "name李四1"],
["id5", "name李四5"]
];
let obj = [];
let str;
arrays = arrays.reduce((item, next) => {
str = next.toString();
obj.indexOf(str) == -1 ? item.push(next) && obj.push(str) : '' ;
return item;
}, []);
console.log(arrays.toString())
网友评论