loading...

Solving "Wherefore art thou" / freeCodeCamp Algorithm Challenges

virenb profile image Viren B Originally published at virenb.cc ・4 min read

Solving freeCodeCamp's Algorithm Challenges (37 Part Series)

1) FCC Algorithm Challenges / Convert Celsius to Fahrenheit 2) FCC Algorithm Challenges / Reverse a String 3 ... 35 3) FCC Algorithm Challenges / Factorialize a Number 4) FCC Algorithm Challenges / Find the Longest Word in a String 5) FCC Algorithm Challenges / Return Largest Numbers in Arrays 6) Solving "Confirm the Ending" / FreeCodeCamp Algorithm Challenges 7) Solving "Repeat a String Repeat a String" / FreeCodeCamp Algorithm Challenges 8) Solving "Truncate a String" / freeCodeCamp Algorithm Challenges 9) Solving "Finders Keepers" / freeCodeCamp Algorithm Challenges 10) Solving "Boo who" / freeCodeCamp Algorithm Challenges 11) Solving "Title Case a Sentence" / freeCodeCamp Algorithm Challenges 12) Solving "Slice and Splice" / freeCodeCamp Algorithm Challenges 13) Solving "Falsy Bouncer" / freeCodeCamp Algorithm Challenges 14) Solving "Where do I Belong" / freeCodeCamp Algorithm Challenges 15) Solving "Mutations" / freeCodeCamp Algorithm Challenges 16) Solving "Chunky Monkey" / freeCodeCamp Algorithm Challenges 17) Solving "Sum All Numbers in a Range" / freeCodeCamp Algorithm Challenges 18) Solving "Diff Two Arrays" / freeCodeCamp Algorithm Challenges 19) Solving "Seek and Destroy" / freeCodeCamp Algorithm Challenges 20) Solving "Wherefore art thou" / freeCodeCamp Algorithm Challenges 21) Solving "Spinal Tap Case" / freeCodeCamp Algorithm Challenges 22) Solving "Pig Latin" / freeCodeCamp Algorithm Challenges 23) Solving "Search and Replace" / freeCodeCamp Algorithm Challenges 24) Solving "DNA Pairing" / freeCodeCamp Algorithm Challenges 25) Solving "Missing letters" / freeCodeCamp Algorithm Challenges 26) Solving "Sorted Union" / freeCodeCamp Algorithm Challenges 27) Solving "Convert HTML Entities" / freeCodeCamp Algorithm Challenges 28) Solving "Sum All Odd Fibonacci Numbers" / freeCodeCamp Algorithm Challenges 29) Solving "Sum All Primes" / freeCodeCamp Algorithm Challenges 30) Solving "Smallest Common Multiple" / freeCodeCamp Algorithm Challenges 31) Solving "Drop it" / freeCodeCamp Algorithm Challenges 32) Solving "Steamroller" / freeCodeCamp Algorithm Challenges 33) Solving "Binary Agents" / freeCodeCamp Algorithm Challenges 34) Solving "Everything Be True" / freeCodeCamp Algorithm Challenges 35) Solving "Arguments Optional" / freeCodeCamp Algorithm Challenges 36) Solving "Make a Person" / freeCodeCamp Algorithm Challenges 37) Solving "Map the Debris" / freeCodeCamp Algorithm Challenges

'Wherefore art thou'

Let's solve 'Wherefore art thou' another Intermediate JavaScript Algorithm Scripting Challenge, from freeCodeCamp. Here is what we are working with:

STARTER CODE

function whatIsInAName(collection, source) {
  var arr = [];
  // Only change code below this line


  // Only change code above this line
  return arr;
}

whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });

INSTRUCTIONS

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). Each name and value pair of the source object has to be present in the object from the collection if it is to be included in the returned array.

For example, if the first argument is [{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], and the second argument is { last: "Capulet" }, then you must return the third object from the array (the first argument), because it contains the name and its value, that was passed on as the second argument.

TESTS

whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" }) should return [{ first: "Tybalt", last: "Capulet" }].
whatIsInAName([{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }], { "apple": 1 }) should return [{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }].
whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 }) should return [{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }].
whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "cookie": 2 }) should return [{ "apple": 1, "bat": 2, "cookie": 2 }].
whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }, { "bat":2 }], { "apple": 1, "bat": 2 }) should return [{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie":2 }].
whatIsInAName([{"a": 1, "b": 2, "c": 3}], {"a": 1, "b": 9999, "c": 3}) should return []

Our Thoughts & Approach

The most important part of solving algorithm challenges is reading. Reading the starter code, the directions, and the tests thoroughly is the approach I take before jumping into coding. If the objective is not understood, I believe it will be a lot harder to code a solution. So what we are working with it is:

  • Our two inputs are an array of objects (collection) and an object (source).

  • We want our ouput to be an array.

  • We need to check if the second argument exists in the first argument (check if the key(s) exists).

Since we are working with objects and arrays in this challenge, let us see if there are any built-in methods we can use to help solve this.

After reading all the information, my first action would be to use a method, Object.keys(), on the second argument, source, to create an array from the keys of the object. I feel it would be easier to check against collection.

Object.keys() on MDN

let source = { "apple": 1, "bat": 2 };
console.log(Object.keys(source));
// Array [ "apple", "bat" ]

So we now have an array of objects and an array (of keys to check). The natural instinct (for me) is to now loop through collection, but we want to check if the keys exist and then also check the values.

An array method we've used in the past to check if a test (that we set up) passes is Array.filter(). It will create a new array of the items which pass the test.

Array.filter()

One possible issue I can see is the fact we are looping through an array but we need to access an object within the array, not just primitive data types (string, number, etc.).

Reading up more about objects, there is a method for which you can check if the property exists on the object. Example below:

let dog = {name: 'Rusty', age: 4};
console.log(dog.hasOwnProperty('name'));
// true

Object.hasOwnProperty() on MDN

So, in short, we're going to use arr, an empty array already declared, set that to collection.filter(), loop through collection, use hasOwnProperty() to see if the key exists in the objects within collection, then check if the values are equal, returning the items which are two. Let's break that down a little further:

var arr = []; // This code was provided
var sourceKeys = Object.keys(source) // Creates an array of keys
arr = collection.filter(function(obj) {
  // obj is each item (an object) in collection
  for (var i = 0; i < sourceKeys.length; i++) {
    // we want to loop through based on how many keys they're were in source
    if (!obj.hasOwnProperty(sourceKeys[i]) || obj[sourceKeys[i]] !== source[sourceKeys[i]])   
      // if obj doesnt have the key OR if obj key's value doesn't equal source key's value
      // return false so it get's filtered out
    {
      return false;
    }
  }
  return true;
  // if it passed the above if statement, doesn't get filtered out and goes into arr
})
return arr;
// return an array

I didn't use pseudocode this time but I hope the comments were helpful.

Our Solution

function whatIsInAName(collection, source) {
  var arr = [];
  // Only change code below this line
  var sourceKeys = Object.keys(source);
  arr = collection.filter(function(obj) {
    for (var i = 0; i < sourceKeys.length; i++) {
      if (!obj.hasOwnProperty(sourceKeys[i]) || obj[sourceKeys[i]] !== source[sourceKeys[i]]) {
        return false;
      }
    }
    return true;
  })
  // Only change code above this line
  return arr;
}

Resources & Links

'Wherefore art thou' challenge on fCC

freeCodeCamp

Donate to freeCodeCamp

My Solution on GitHub

Thank you for reading!

Solving freeCodeCamp's Algorithm Challenges (37 Part Series)

1) FCC Algorithm Challenges / Convert Celsius to Fahrenheit 2) FCC Algorithm Challenges / Reverse a String 3 ... 35 3) FCC Algorithm Challenges / Factorialize a Number 4) FCC Algorithm Challenges / Find the Longest Word in a String 5) FCC Algorithm Challenges / Return Largest Numbers in Arrays 6) Solving "Confirm the Ending" / FreeCodeCamp Algorithm Challenges 7) Solving "Repeat a String Repeat a String" / FreeCodeCamp Algorithm Challenges 8) Solving "Truncate a String" / freeCodeCamp Algorithm Challenges 9) Solving "Finders Keepers" / freeCodeCamp Algorithm Challenges 10) Solving "Boo who" / freeCodeCamp Algorithm Challenges 11) Solving "Title Case a Sentence" / freeCodeCamp Algorithm Challenges 12) Solving "Slice and Splice" / freeCodeCamp Algorithm Challenges 13) Solving "Falsy Bouncer" / freeCodeCamp Algorithm Challenges 14) Solving "Where do I Belong" / freeCodeCamp Algorithm Challenges 15) Solving "Mutations" / freeCodeCamp Algorithm Challenges 16) Solving "Chunky Monkey" / freeCodeCamp Algorithm Challenges 17) Solving "Sum All Numbers in a Range" / freeCodeCamp Algorithm Challenges 18) Solving "Diff Two Arrays" / freeCodeCamp Algorithm Challenges 19) Solving "Seek and Destroy" / freeCodeCamp Algorithm Challenges 20) Solving "Wherefore art thou" / freeCodeCamp Algorithm Challenges 21) Solving "Spinal Tap Case" / freeCodeCamp Algorithm Challenges 22) Solving "Pig Latin" / freeCodeCamp Algorithm Challenges 23) Solving "Search and Replace" / freeCodeCamp Algorithm Challenges 24) Solving "DNA Pairing" / freeCodeCamp Algorithm Challenges 25) Solving "Missing letters" / freeCodeCamp Algorithm Challenges 26) Solving "Sorted Union" / freeCodeCamp Algorithm Challenges 27) Solving "Convert HTML Entities" / freeCodeCamp Algorithm Challenges 28) Solving "Sum All Odd Fibonacci Numbers" / freeCodeCamp Algorithm Challenges 29) Solving "Sum All Primes" / freeCodeCamp Algorithm Challenges 30) Solving "Smallest Common Multiple" / freeCodeCamp Algorithm Challenges 31) Solving "Drop it" / freeCodeCamp Algorithm Challenges 32) Solving "Steamroller" / freeCodeCamp Algorithm Challenges 33) Solving "Binary Agents" / freeCodeCamp Algorithm Challenges 34) Solving "Everything Be True" / freeCodeCamp Algorithm Challenges 35) Solving "Arguments Optional" / freeCodeCamp Algorithm Challenges 36) Solving "Make a Person" / freeCodeCamp Algorithm Challenges 37) Solving "Map the Debris" / freeCodeCamp Algorithm Challenges

Posted on by:

virenb profile

Viren B

@virenb

Self-taught developer, always looking to learn more.

Discussion

markdown guide
 

Another way:

const whatIsInAName = (objs, obj) =>
  objs.filter(
    e => Object.entries(obj).every(
      ([k, v]) => e?.[k] === v
    )
  )