Solving "Wherefore art thou" / freeCodeCamp Algorithm Challenges
Tags: freecodecamp, algorithms, challenge, javascript
Published: 2020-07-08 18:39:12

---
title: Solving "Wherefore art thou" / freeCodeCamp Algorithm Challenges
published: true
description: My guide, notes, and solution to freeCodeCamp's basic algorithm challenge, "Wherefore art thou" 
tags: #freeCodeCamp, #algorithms, #challenge, #javascript
canonical_url: https://virenb.cc/fcc-020-wherefore-art-thou
series: Solving freeCodeCamp's Algorithm Challenges
---
!['Wherefore art thou'](//images.ctfassets.net/yzwpq1epaq68/1YzuHCI7qPy0pn2rOtcTWK/220444142bf7606f839054075d5beb69/ss-020.png)

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

### STARTER CODE

```javascript
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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys "MDN: Object.keys()")


```javascript
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()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter "MDN: 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:


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


[Object.hasOwnProperty() on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty "hasOwnProperty() docs")


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:


```javascript
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

```javascript
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](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/wherefore-art-thou "fCC Challenge")

[freeCodeCamp](https://www.freecodecamp.org/ "fCC")

[Donate to freeCodeCamp](https://www.freecodecamp.org/donate/ "fCC Donation Page")

[My Solution on GitHub](https://github.com/virenb/fcc-algorithms/blob/master/020---wherefore-art-thou.js "GitHub Solution")


Thank you for reading!