Leroy
Leroy

Reputation: 56

How to check an array of objects is totally belongs to another?

There are two array of objects like this

var a = [
  {id:'1'},
  {id:'2'}
];
var b = [
  {id:'1',name:'a'},
  {id:'2',name:'b'},
  {id:'3',name:'c'}
]

And I need a function, if all ids of the elements of array a can be found in array b, it will return true, otherwise return false

Upvotes: 0

Views: 77

Answers (5)

dziraf
dziraf

Reputation: 3653

Solution using Array.prototype.filter and Array.prototype.some:

const includeCheck = (a, b) => {
  if (b.filter(el => a.some(obj => obj.id === el.id)).length === b.length) {
console.log('b fully includes a')
  } else {
console.log('b does not fully include a')
  }
}

let a = [{id:'1'}, {id:'2'}, {id:'3'}], 
b = [{id:'1',name:'a'}, {id:'2',name:'b'}, {id:'3',name:'c'}]
    
includeCheck(a, b);

It compares lengths of original b array and b array filtered by a array's ids to determine whether b has all a ids or not.

Upvotes: 0

protoproto
protoproto

Reputation: 2099

Can use this simple way:

var a = [
  {id:'1'},
  {id:'2'}
];
var b = [
  {id:'1',name:'a'},
  {id:'2',name:'b'},
  {id:'3',name:'c'}
];

var id_a = a.map((current)=>{
    return current.id;
}); console.log(id_a); // ["1", "2"]

var id_b = b.map((current)=>{
    return current.id;
}); console.log(id_b); // ["1", "2", "3"]

// check if id_a in id_b, check total element of each set
let bool = Array.from(new Set(id_b) ).length == Array.from(new Set(id_b.concat(id_a)) ).length;
console.log(bool);

Upvotes: 0

pencil a
pencil a

Reputation: 91

You can use the following

var a = [
  {id:'1'},
  {id:'2'}
];
var b = [
  {id:'1',name:'a'},
  {id:'2',name:'b'},
  {id:'3',name:'c'}
]
console.log(checkobject());
function checkobject()
{
var checkid=true;
a.forEach(function(el)
{
 
   var check=b.findIndex(function(element) {
       return element.id===el.id;
   });
   if(check==-1)
   {
   checkid=false;
   return;
   }
    
});
  return checkid;
}

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386560

You could use a Set and check with Array#every.

const check = (a, b) => a.every((s => ({ id }) => s.has(id))(new Set(b.map(({ id }) => id))));

var a = [{ id: '1' }, { id: '2' }],
    b = [{ id: '1', name: 'a' }, { id: '2', name: 'b' }, { id: '3', name: 'c' }];
    
console.log(check(a, b));

Upvotes: 1

OliverRadini
OliverRadini

Reputation: 6467

This is not the most efficient way, as it needs to create the list of ids in b for each item in a.

var a = [
  {id:'1'},
  {id:'2'},
  {id:'7'},
];
var b = [
  {id:'1',name:'a'},
  {id:'2',name:'b'},
  {id:'3',name:'c'}
]

const allPresent = a
  .map(item => item.id)
  .map(id => Object.assign({
    id,
    present: b
      .map(item => item.id)
      .indexOf(id) > -1,
  }))


console.log(allPresent)

Upvotes: 0

Related Questions