Reputation: 29
I have two arrays that contain objects. From first array how can I remove the items that are already present in the second array?
First array:
var s = [
{"Name": "1"},
{"Name": "2"},
{"Name": "3"},
{"Name": "4"},
{"Name": "5"},
{"Name": "6"}
]
Second array:
var t = [
{"Name": "1"},
{"Name": "2"},
{"Name": "3"},
{"Name": "8"}
]
Expected output:
[
{"Name": "4"},
{"Name": "5"},
{"Name": "6"}
]
Upvotes: 0
Views: 185
Reputation: 726
z = f(s, t);
function f(first, second) {
var z = [];
for (var i = 0; i < first.length; i++) {
var included = false;
for (let j = 0; j < second.length; j++) {
if(equal(first[i], second[j]))
included = true;
//break; //optional
}
if(!included)
z.push(first[i]);
}
return z;
}
function equal(a,b){
//however you define the objs to be equal
return a.Name == b.Name;
}
Upvotes: 0
Reputation: 38552
You can use filter()
along with some()
var s = [{"Name":"1"},{"Name":"2"},{"Name":"3"},{"Name":"4"},{"Name":"5"},{"Name":"6"}];
var t = [{"Name":"1"},{"Name":"2"},{"Name":"3"},{"Name":"8"}];
result = s.filter(a => !t.some(b => a.Name === b.Name));
console.log(result);
Upvotes: 1
Reputation: 3345
An approach using set and .filter method
var s=[
{
"Name": "1"
},
{
"Name": "2"
},
{
"Name": "3"
},
{
"Name": "4"
},
{
"Name": "5"
},
{
"Name": "6"
}
];
var t= [
{
"Name": "1"
},
{
"Name": "2"
},
{
"Name": "3"
},{
"Name": "8"
}
];
var set = new Set();
t.forEach(obj => set.add(obj.Name));
s=s.filter(obj => !set.has(obj.Name))
console.log(s);
Upvotes: 0