0

Consider below two arrays of objects:

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}
];

Comparison of these two objects must return false because there are values for prop id in arr2 that are missing in arr1 (namely id: 4).

At this point, the below attempt has been made:

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

NOTE: Suppose arr2 was:

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

The comparison must return true, since the id of every element in arr2 is found in arr1's elements.

2
  • arr1.every(i => arr2.map(z => z.id).includes(i.id)) <--- please try this & share feedback. Commented Feb 17, 2022 at 12:32
  • 1
    There has to be a good original question to point this at... Commented Feb 17, 2022 at 12:36

1 Answer 1

3

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);

Sign up to request clarification or add additional context in comments.

2 Comments

Very elegant !! May be the other way around is also required. This checks if every arr1 element is present in arr2. May be the OP also requires to check if every arr2 element is present in arr1 too?
@jsN00b - Actually, I had it the wrong way around to start with. :-) Noticed when I did the live example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.