DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 73

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) {

}
Enter fullscreen mode Exit fullscreen mode

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}
] 
Enter fullscreen mode Exit fullscreen mode

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'}, 
  ...
] 
Enter fullscreen mode Exit fullscreen mode

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);
  }
Enter fullscreen mode Exit fullscreen mode

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;
  })
Enter fullscreen mode Exit fullscreen mode

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;
  })
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)