Lu Do
Lu Do

Reputation: 97

How to check if an array of objects contains all the ids of another array of objects JS

I have 2 arrays of Objects;

// First one :
[0: {id: 1},
1: {id: 2},
2: {id: 3},
3: {id: 4}]

// Second one :
[0: {id: 10},
1: {id: 1},
2: {id: 4},
3: {id: 76},
4: {id: 2},
5: {id: 47},
6: {id: 3}]

I'd like to test if the second one has at least every same IDs of the first one. Which would be true in this case because the second one contains 1, 2, 3 and 4 IDs.

I tried to use some() and every() but it doesn't work properly

My try :

let res = this.trainingEpisodesList.some( episode => {
    this.completedEpisodes.every( userEpisode => {
         userEpisode.id == episode.id;
     })
});

Thanks ;)

Upvotes: 2

Views: 6443

Answers (2)

ES7,

let result = one.map(a => a.id);
let result2 = two.map(a => a.id);
const final_result = result.every(val => result2.includes(val));

ES5,

var result = one.map(a => a.id);
var result2 = two.map(a => a.id);

var final_result = result.every(function(val) {

  return result2.indexOf(val) >= 0;

});

Upvotes: 4

Majed Badawi
Majed Badawi

Reputation: 28414

You can do this using every and find:

let completedEpisodes = 
[
{id: 1},
{id: 2},
{id: 3},
{id: 4}
]

let trainingEpisodesList = 
[
{id: 10},
{id: 1},
{id: 4},
{id: 76},
{id: 2},
{id: 47},
{id: 3}
]

let containsAllCompleted = trainingEpisodesList.every(c => completedEpisodes.find(e=>e.id==c.id));

console.log(containsAllCompleted);

Upvotes: 3

Related Questions