I am trying to exclude some elements from array items
that include properties from array excludes
.
I wrote this code which works fine. However, due to nested iterations, time complexity is O(n^3). Is there a way to do better?
const items = [
{ color: 'red', type: 'tv', age: 18 },
{ color: 'silver', type: 'phone', age: 20 },
{ color: 'blue', type: 'car', age: 18 },
{ color: 'green', type: 'tv', age: 10 },
{ color: 'gold', type: 'phone', age: 7 },
{ color: 'orange', type: 'car', age: 2 },
];
const excludes = [
{ k: 'color', v: 'red' },
{ k: 'color', v: 'blue' },
{ k: 'type', v: 'phone' },
];
function excludeItems(items, excludes) {
let ref = new Map();
excludes.forEach((pair) => {
if (!ref.has(pair.k)) {
ref.set(pair.k, []);
}
ref.get(pair.k).push(pair.v);
});
ref.forEach((value, key) => {
items = items.filter(
(item) => !value.some((element) => element == item[key]),
);
});
return items;
}
This is the console output (which is correct):
Remaining Items: [
{ color: 'green', type: 'tv', age: 10 },
{ color: 'orange', type: 'car', age: 2 }
]