isSubset
Test that an object with an array is a subset of another
by Michel Plungjan
JavaScript
ObjectA = {
title: 'Alita: Battle Angel',
year: '2019',
casts: ['Rosa Salazar',
'Christoph Waltz',
'Jennifer Connelly',
'Mahershala Ali',
'Michelle Rodriguez',
'Casper Van Dien'
]
}
ObjectB = {
title: 'Alita: Battle Angel',
casts: ['Rosa Salazar',
'Christoph Waltz'
],
year: '2019'
}
function isSubset(a, b) {
let count = 0;
let length = Object.keys(b).length; // the shortest
let subset = Object.entries(b).map((item, cnt) => {
let key = item[0];
let val = item[1];
if (Array.isArray(val)) {
if (val.every(val => a[key].includes(val))) count++;
}
else if (val === a[key]) count++
})
return count === length;
}
console.log(isSubset(ObjectA,ObjectB));