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"}
]
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);
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);
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.