Reputation: 56
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
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
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
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
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
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