Wherefore Art Thou: FCC Algorithm Scripting

jackLyons Free Code Camp Tags: ,
2

In this post I’m going to explain how to unravel the tricky algorithm challenge called Wherefore Art Thou. At first, it seems really overwhelming with all that data being thrown at you. But with the help of the new ES 6 Array helper methods like filter and every things truly do become much clearer. It is really worth putting in some time to learn about ES6 and what it can do for you. But without further ado, lets get started!

Useful links:

There’s a lot going on in this problem, and these links above are worth reading up on. In general, I think it is totally worth your while to learn up about how Arrays can be manipulated with the new ES6 Array helpers. By learning how to apply reduce, filter, find, map on an Array I guarantee that you will find so much more clarity in each and every problem you go to solve. Here’s a pretty awesome course over at Udemy which will teach you all about front end web development using ES6.

How to solve the problem:

1. Find the key.

If you read up on the hints above, you’ll notice that we can use the new Object.keys() method which makes it easier to iterate through a collection of data. It’s just like the for … in  loop but easier and less verbose. So we will be using this to create a variable that will act as the source key for the item we are looking for.

var sourceKey = Object.keys(source);

2. Setup your filter.

The filter method is a really valuable tool when it comes to sifting through data. As a front end web developer (now currently employed, and yes it was thanks to my Free Code Camp portfolio!) I never thought I would do much work with data. To me, I thought that was all just “backend stuff”. At first, I thought all these FCC problems were a bit unrealistic because programming really did feel way out of my league, but the more I actually work on real-world projects the more I realise how valuable my FCC education has been. So that being said, I recommend you get used to the filter method:

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Using the same syntax as the other Array helpers like map and every, the filter method can be refactored into ES6 by writing the code as follows:

function isBigEnough(value) {
  var nums = [12, 5, 8, 130, 44];
  return filtered.filter(function(num) {
    return num > 10;
  });
}
/*------------------
/ Now with ES6  /
------------------*/
function isBigEnough(value) {
  var nums = [12, 5, 8, 130, 44];
  return nums.filter(num => num > 10);
}

Notice the arrow sign instead of writing return as well as the removed braces due to the fact that there is only one variable. It’s cheeky, which allows you to write all your code into one line. Of course, it can sometimes be hard to read if you aren’t used to it, and maybe it’s not always recommended when writing code that needs to be shared around an office of varying levels of JS experience. But hey, this is what we will be seeing more of in the future, so it’s best to get up to speed sooner than later.

In the case of this problem, we want to filter a given collection of data:


function whatIsInAName(collection, source) {
  var sourceKey = Object.keys(source);
  return collection.filter((itemInCollection) => {
  // code goes here...
  });
}

3. Check every object in the collection

So with the given code, me must now dive another level deeper. Nesting functions can sometimes get confusing so always remember to create your opening and closing brackets and parentheses at the same time.

Again, ES6 comes to the rescue with a simple Array helper called every. The name says it all, because this helper is used to check every item within an array and only return true or false when the specified condition is met with every item in the array. In other words, if every item in the array or object meets the condition then every returns true, otherwise false. You can read more about it at this link.

Using every, we will check the keys of the source argument against all the items within the collection argument. To do this, we can use the .hasOwnProperty() method, which was given to us in the hints above. This helps us compare and check for a match.

Alternatively, we can just check and compare using bracket notation, which is much easier to a.) understand, and b.) write in JS. It looks like this:


return sourceKey.every((keyInObject) => {
  return itemInCollection[keyInObject] === source[keyinObject];
}); 

For every key within every item within the collection argument, check if the source arguments key matches. If it does, simply return the object from the collection in it’s entirety. Woah, that was a mouthful. If you’re still a bit confuzzled on all of this, then I highly recommend this awesome course over at Udemy which will teach you all about how to use ES6 in the real world.

4. Wrap it all up, and don’t forget to always return your result!

One of the biggest things worth mentioning with all these fancy ES6 Array helpers is that for every function you write you’ve got to remember to include the return keyword. Otherwise you’ll end up producing a new array filled with undefined items. This has happened to me a fair few times and I was always scratching me head wondering why my code wasn’t working! In the answer below you can see there are 3 return statmenets: one for the filter, one for the every function, and a final one for the end result.

Check the result below:


function whatIsInAName(collection, source) {
  var sourceKey = Object.keys(source); 
  return collection.filter((itemInCollection) => { 
    return sourceKey.every((keyInObject) => { 
      return itemInCollection[keyInObject] === source[keyinObject]; 
    }); 
  }); 
}

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

Answer: { first: “Tybalt”, last: “Capulet” }

If you have any questions, comments or feedback then please leave a note in the comment’s box below!


The Web Developers Bootcamp.

A n00b friendly guide to becoming a pro!

If you’re feeling a bit overwhelmed and a little lost with all these crazy hard Free Code Camp exercises then this course is for you!

While I am oh so grateful for the opportunity to learn through Free Code Camp, I still find that learning to code alone and without proper guidance extremely exhausting. Which is why I’ve started to substitute my education with an incredible online resource called the Web Developers Bootcamp courtesy of Udemy.

This course has helped me brush off the cobwebs, unlearn my self-taught bad habits and gain a solid understanding of the true fundamentals of web development. It has helped me see why it is important to understand these JavaScript problems and how they apply to the real world.

This bootcamp will teach you how built beautiful sites with Bootstrap, add in functionality with JavaScript and write back end code with Node.js all in a series of short, sharp, no BS video modules. I seriously could not recommend it any higher. Check it out and let me know what you think 🙂

The Web Developers Bootcamp
The Web Developer Bootcamp.
The only course you need to learn web development – HTML, CSS, JS, Node, and More!

  • Greg Brewton

    This is the sixth or seventh “solution” I’ve tried for the What’s In a Name challenge on FCC and I am still just as confused as I was eight hours ago when I started trying to figure it out. You can’t use es6 on FCC, you get warning triangles. Is there anyone who can explain how to solve this, why it works, what these functions actually do, and all within the constraints set forth by the instructions in FCC?

    • Hi Greg, sure you can use ES6 in FCC. They just warn you not to. ES6 is perfectly fine and in many ways it reduces the amount code you actually have to write. If you are really worried about using it, then you can always “polyfill” your code. Alternatively, you can just use for loops to the same effect.

      If you are really confused, then I would recommend that you take a course on ES6. Otherwise, you need to use for loops to go through the array of objects. Honestly, try to solve it however best suits your coding style.

Sign up to receive up-to-date web tips, tricks and code hacks!