目录
双层for循环:
indexof():
map方法(推荐):
双层for循环:
//双层for循环
let arrObj = [{
name: "小红",
id: 1
},
{
name: "小橙",
id: 1
},
{
name: "小黄",
id: 4
},
{
name: "小绿",
id: 3
},
{
name: "小青",
id: 1
},
{
name: "小蓝",
id: 4
}
];
function ridding(arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i].id == arr[j].id) {
arr.splice(j, 1)
}
}
}
return arr;
}
console.log(ridding(arrObj))
indexof():
function fn2(arrObj) {
let newArr = [];
for (let i = 0; i < arrObj.length; i++) {
if (newArr.indexOf(arrObj[i].id) == -1) {
console.log(i, newArr.indexOf(arrObj[i].id));
newArr.push(arrObj[i].id);
} else {
console.log(i, newArr.indexOf(arrObj[i].id));
arrObj.splice(i, 1);
};
};
return arrObj;
};
console.log(fn2(arrObj));
map方法(推荐):
let map = new Map();
for (let item of arrObj) {
if (!map.has(item.id)) {
map.set(item.id, item)
}
}
let arr = [...map.values()];
console.log(arr);