DEV Community

James Kim
James Kim

Posted on

Intermediate Algorithm Scripting: filter(), every(), and Object.keys() [freeCodeCamp Javascript]

Working through the Intermediate Algorithm Scripting section of freeCodeCamp's Javascript Algorithms and Data Structures Certification, I have come across a challenging problem involving filter(), every(), and Object.keys().

Most of the solutions on the hints page are long and clustered with for loop iterations, that I try to avoid. Even as a beginner, I am trying to utilize ES6 arrow functions and higher order functions, when possible.

So here is the challenge:

Make a function that looks through an array of objects (first argument) and returns an array of all objects that have matching name and value pairs (second argument).

Here is the array of names to filter with a function:

var namesToFilter = 
([
{ first: "Romeo", last: "Montague" }, 
{ first: "Mercutio", last: null }, 
{ first: "Tybalt", last: "Capulet" }
])

var filter =  
({ last: "Capulet" }
)
Enter fullscreen mode Exit fullscreen mode

First, a class function, whatIsInAName will be created containing the arguments collection and source. The function will check and return any array of names ['first', 'last'] in collection that matches the array of names ['first', 'last'] in source.

const whatIsInAName = (collection, source) =>
  collection
    .filter(item => 
      Object.keys(source)
        .every(key =>
          source[key] === item[key]
      )
  )
Enter fullscreen mode Exit fullscreen mode

We will use .filter() to get all item elements of collection that satisfy a certain method's conditions.

  collection
    .filter(item =>
Enter fullscreen mode Exit fullscreen mode

Objects.keys(source) returns the key properties of the source array. In this case, ['last'].

The .every() method requires all key elements of source keys to satisfy the condition that, the key property of source must be the same as the key property of collection's item element.

      Object.keys(source)
        .every(key =>
          source[key] === item[key]
      )
  )
Enter fullscreen mode Exit fullscreen mode

Solution:

whatIsInAName(namesToFilter, filter)
// [ { first: 'Tybalt', last: 'Capulet' } ]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)