I have
array1 = [{ name: sample1 }, { name: sample2 }, { name: sample3 }];
array2 = [{ name: sample1 }, { name: sample2 }];
I want to filter objects of array1
which exists in array2
. So I need to have
[{ name: sample1 }, { name: sample2 }]
How can I get it in javascript?
I guess your objects are not referentially same, so you can try stringifying them and then comparing.
If order of properties can vary then you can consider using a library like lodash<\/a> .
You can use .filter and .some function in JavaScript , Here is the example
const array1 = [{ name: "sample1" }, { name: "sample2" }, {
name: "sample3" }];
const array2 = [{ name: "sample1" }, { name: "sample2" }];
let Result = array1.filter(function(obj) {
return array2.some(function(obj2) {
return obj.name== obj2.name;
});
});
console.log(Result)
You can use object destructuring, the map()<\/code> and
.includes()<\/code> methods as shown below:
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.