// Could be potentially more than 3 keys in the object above
const items = [{
color: 'red',
type: 'tv',
age: 18
},
{
color: 'silver',
type: 'phone',
age: 20
},
{
color: 'yellow',
type: 'truck',
age: 10
},
{
color: 'blue',
type: 'shirt',
age: 5
},
];
const excludes = [{
k: 'color',
v: 'silver'
},
{
k: 'type',
v: 'tv'
},
{
k: 'color',
v: 'red'
}
];
// SOLUTION
const excludesMap = excludes.reduce((acc, curr) => {
if (!acc[curr.k]) {
acc[curr.k] = {};
}
acc[curr.k][curr.v] = true;
return acc;
}, {});
/*
color: red: true,
green: true ...
type: tv: true
truck: true, ...
*/
const exclude = (items, excludes) => items.filter(item => {
for (let key in item) {
if (item.hasOwnProperty(key) &&
excludesMap[key] &&
excludesMap[key][item[key]])
return false;
}
return true;
});
console.log(exclude(items, excludes));
// Output:
// [{color: "yellow", type: "truck", age: 10},
// {color: "blue", type: "shirt", age: 5}]
Categories