Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if an array of objects contains every other element of an array of objects based on a property

given those arrays

arr1 = [
{name: "name1", id: 1},
{name: "name2", id: 2},
{name: "name3", id: 3}
]

arr2 = [
{name: "name1", id: 1},
{name: "name2", id: 4},
{name: "name3", id: 3}
]

The case above should return false, because arr2[1].id (4) doesn’t exist on arr1

I pretty much, must check that every element of arr2 exists on arr1 , based on its id

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I was thinking something like

arr1.every(i => i.id === arr2.map(z =>z.id))

But im not really sure

If arr2 was

arr2 = [
    {name: "name1", id: 1},
    {name: "name3", id: 3}
    ]

It should return true, because every el of arr2, exists in arr1

>Solution :

You’re relaly close, but map is for mapping each element of the array to some new value, not for seeing if an element exists. You’d use some for that, and you’d want to reverse the arrays you’re calling every and some on:

const flag = arr2.every(element => arr1.some(({id}) => id === element.id));

That says: "Does every element of arr2 have at least one matching element in arr1 by id?"

Live Example:

const arr1 = [
    {name: "name1", id: 1},
    {name: "name2", id: 2},
    {name: "name3", id: 3}
];

const arr2 = [
    {name: "name1", id: 1},
    {name: "name2", id: 4},
    {name: "name3", id: 3}
];

const arr3 = [
    {name: "name1", id: 1},
    {name: "name3", id: 3}
];

const result1 = arr2.every(element => arr1.some(({id}) => id === element.id));
console.log("arr2 and arr1: " + result1);

const result2 = arr3.every(element => arr1.some(({id}) => id === element.id));
console.log("arr3 and arr1: " + result2);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading