The task is to implement the function excludeItems. The function removes items from an array that match any key-value conditions in the excludes list.
The boilerplate code:
function excludeItems(items, excludes) {
}
This is an example of items in an array
let items = [
{color: 'red', type: 'tv', age: 18},
{color: 'silver', type: 'phone', age: 20},
{color: 'blue', type: 'book', age: 17}
]
This is an example of things to exclude from the array using the excludeItems function
const excludes = [
{k: 'color', v: 'silver'},
{k: 'type', v: 'tv'},
...
]
Create a set that converts all the rules into a structure that is easy to check quickly. For each item, check if the value appears in the exclude set. If it does not, keep it.
const excludeMap = {}
for(const{k,v} of excludes) {
if(!excludeMap[k]) excludeMap[k] = new Set();
excludeMap[k].add(v);
}
If the value appears in the exclude set, remove it
return items.filter(item => {
for(const key in excludeMap) {
if(excludeMap[key].has(item[key])) return false;
}
return true;
})
The scanning of the whole list is done just once. The final code
function excludeItems(items, excludes) {
const excludeMap = {}
for(const{k,v} of excludes) {
if(!excludeMap[k]) excludeMap[k] = new Set();
excludeMap[k].add(v);
}
return items.filter(item => {
for(const key in excludeMap) {
if(excludeMap[key].has(item[key])) return false;
}
return true;
})
}
That's all folks!
Top comments (0)