javascript - How to check if an array of objects contains all the ids of another array of objects JS - Stack Overflow

I have 2 arrays of Objects; First one :[0: {id: 1},1: {id: 2},2: {id: 3},3: {id: 4}] Second on

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 => {
    thispletedEpisodes.every( userEpisode => {
         userEpisode.id == episode.id;
     })
});

Thanks ;)

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.pletedEpisodes.every( userEpisode => {
         userEpisode.id == episode.id;
     })
});

Thanks ;)

Share Improve this question edited Aug 30, 2020 at 20:47 arhak 2,5521 gold badge27 silver badges39 bronze badges asked Aug 30, 2020 at 18:05 Lu DoLu Do 971 silver badge9 bronze badges 2
  • but it doesn't work properly is not an error description. What is your expectation and what is the output of your code? – Jens Commented Aug 30, 2020 at 18:08
  • Not returning anything inside of a some or every call is one reason, why your try won't do what you want. I'd also get a better IDE/linter (or configure them properly), a statement like userEpisode.id == episode.id; should be automatically marked as "probably a mistake". – ASDFGerte Commented Aug 30, 2020 at 18:15
Add a ment  | 

2 Answers 2

Reset to default 4

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;

});

You can do this using every and find:

let pletedEpisodes = 
[
{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 => pletedEpisodes.find(e=>e.id==c.id));

console.log(containsAllCompleted);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744178732a4561879.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信