var arr=[{'id':1,'name':1},{'id':2,name:2},{'id':3,'name':3}];
var obj = {'id':2,'name':2};
How to compare arr and obj? After discovering that id2 is repeated, remove the array object id:2 of arr and generate a new array?
Use the array filter to filter to generate a new array.
In addition, the second part of the array in the question 'id:2'
has a grammatical error and the quotation marks are in the wrong position
var res = arr.filter(function(e){
return e.id!=obj.id
})
The following is my imagination: What if the key point of the question is that the key-value pairs are repeated before filtering... (I may be overthinking)
Considering that you may also want to ensure that the key-value pairs of the elements in the array must be exactly the same as the key-value pairs of obj: you can consider this
var arr=[{'id':1,'name':1},{id:2,name:3},{'id':3,'name':3}];
var arr2=[{'id':1,'name':1},{id:2,name:2},{'id':3,'name':3}];
var obj = {'id':2,'name':2};
var res = arr.filter(function(e){//
var result = true; //作為過濾標(biāo)識
for(var key in obj){//遍歷obj的鍵值
if(e[key]!=obj[key]){//如果出現(xiàn)鍵值相同當(dāng)值不同,就不算重復(fù)
result = true;
break;
}
//如果上面條件不通過,那就表示鍵值重復(fù)
result = false;
}//遍歷到最后,如果鍵值都重復(fù),那result肯定是false,否則必然出現(xiàn)result=true的情況
return result;
});
var res2 = arr.filter(function(e){
var result = true;
for(var key in obj){
if(e[key]!=obj[key]){
result = true;
break;
}
result = false;
}
return result;
});
var arr=[{'id':1,'name':1},{'id':2,name:2},{'id':3,'name':3}];
var obj = {'id':2,'name':2};
var index = -1;
for (let i = 0; i < arr.length; i++) {
let flag = false;
for (let item in obj) {
if (obj[item] !== arr[i][item]) {
flag = true;
}
}
if (!flag) {
index = i;
}
}
console.log(index);
arr.splice(index,index>0);
console.log(arr);
Array.prototype.filter()
var arr=[{'id':1,'name':1},{'id':2,name:2},{'id':3,'name':3}];
var obj = {'id':2,'name':2};
var newArray = arr.filter((obj_)=>(obj_.id !== obj.id))