Less is More - Sexy JavaScript Array Transformations

Words
254
Reading
2 min
Listen
Play
9y

Less is More - Sexy JavaScript Array Transformations

For the coding bootcamp I am starting up next week, I've had some prepwork and have been learning about more advanced JavaScript techniques... and wow, what cool stuff! Here is an example where JavaScript can go from plain to sexy with a few sneaky techniques.


Filtering an Array of Data

Scenario: Let's say I have an array of data (we'll use Steem Witnesses and their made up favorite pizza ).

var witness_array = [
   {name: "good-karma", favorite_pizza: "hawaiian"},
   {name: "gtg", favorite_pizza: "pepperoni"},
   {name: "jesta", favorite_pizza: "cheese"},
   {name: "timcliff", favorite_pizza: "hawaiian"},
   {name: "roelandp", favorite_pizza: "cheese"}
];

Now, let's say I want to filter the array so I only get the array of witnesses who share my taste in pizza. How would I do that?

Normal solution: most normal people would say "Rob, why not just loop over the array and filter out the witnesses who have a bad taste in pizza?" So this is what I'd do:

var filtered_array = [];
for (var i = 0; i < witness_array.length < i ++){
    if (witness_array[i].favorite_pizza === "hawaiian") filtered_array.push(witness_array[i]);
}

This would return a filtered array with only good-karma and timcliff. But, this code is ugly and hard to read. If I passed on my code later to a friend, he may have to spend a few seconds trying to figure out what's going on in this loop.

So, I propose a different approach: how about we use some of JavaScript's higher order functions.

Let's use the filter function. The filter function takes an array and filters it by applying a given function to each of it's elements. This function will either return true or false. If the function returns true, the element is added to the new, filtered array. Check it out:

function likesHawaiian(witness){
   return witness.favorite_pizza === "hawaiian";
}
var filtered_array = witness_array.filter(function(witness){
    return likesHawaiian(witness);
});

This is a slight improvement over the normal solution, but not much. It is easy to read; you can see that we are applying the likesHawaiian function to each witness and filtering out the witnesses who don't like hawaiian pizza. BUT this is NOT sexy yet!

Let's make this function sexy.

var filtered_array = witness_array.filter((x) => x.favorite_pizza === "hawaiian");

Wow... we just wrote a more readable, simpler filter function in half as many characters (82 vs. 169). Is it me or did it just get hotter in here?


If you're more interested in the world of functional programming, I recommend you check out: Fun Fun Function's YouTube Channel. If it weren't for this guy, I'd still be writing normal JavaScript code.

I hope you found this article as exciting as I did. Cheers and Steem on!

Less is More - Sexy JavaScript Array Transformations | Ecency