I would like to know how to compare array of objects and array based on conditions using javascript
for the given array of object list
and array arr1
, based on conditions
country
matches with arr1
, return array objectcountry
not matches with arr
, return array objectvar result = list.filter(mem => arr1.includes(mem));
var list =[
{country:"IN", name: "john"},
{country:"SG", name: "peter"}
{country:"MY", name: "zen"}
]
var arr1=["IN", "YU"]
Expected Output
matched list
[
{country:"IN", name: "john"},
{country:"SG", name: "peter"}
]
not matched list
[
{country:"MY", name: "zen"}
]
You'll have to use to use filter
method two times:
const list =[
{country:"IN", name: "john"},
{country:"SG", name: "peter"},
{country:"MY", name: "zen"}
];
const arr1 = ["IN", "YU"];
const matched = list.filter((element) => arr1.includes(element.country));
const notMatched = list.filter((element) => !arr1.includes(element.country));
console.log('Matched List', matched);
console.log('Not Matched List', notMatched);
In the provided example, I'm assuming arr1
contains the country
property that needs to be present in the country
attribute of matched elements, else all others are not matched.
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.