Javascript 30 — Day 4: Array Cardio Day 1

Mike Ekkel
7 min readJan 17, 2017

--

Yesterday was a collection of what I did on days 1 and 2 with the added bonus of learning about CSS variables. The end product? An image editor thingy, yep still calling it that. Today, however, is going to be way different as we are going to work with Arrays and the different methods that we can use.

Check out all the other days over at my table of contents!

Today’s Array methods

When I first started learning JavaScript, these were the bane of my existence. Mainly reduce() because every source I used to learn JavaScript used all these fancy words that you’ll start to use eventually, but make no sense at all when you are starting out. I figured them out eventually, but Wes actually made them more clear now.

If you hadn’t noticed yet, I tend to refer to MDN (Mozilla Developer Network) a lot when it comes to JavaScript, or just the web in general, because they have an amazing library of information that is well written and easy to understand. This article won’t be any different :)

Array.prototype.filter()

The filter() method loops over the Array to create a new Array based upon a test that you write inside the callback function.

const newArray = array.filter(callback())

In Wes’ video we are given an Array of inventors represented as Objects. Each Object has a first name, a last name, year the inventor was born in and year the inventor passed away in. The objective is to filter those who were born in the 1500's.

const fifteen = inventors.filter(function(inventor) {
if(inventor.year >= 1500 && inventor.year < 1600) {
return true;
}
});

This is what is happening with the filter() method:

  1. We pass the method a callback function which takes one argument: the single inventor. The function will be called for each inventor.
  2. We then check if the inventor was born during the 1500’s and return true if that’s the case.
  3. The new Array const fifteen now has all the inventors who returned true.

The callback function can also be written, as you might expect, as an arrow function with an implicit return:

const fifteen = inventors.filter(inventor => (
inventor.year >= 1500 && inventor.year < 1600
));

If you want to know more about the filter() method, go check out MDN. One thing I think is important to know is that filter() doesn’t mutate the Array you call it on. Instead it creates a new array.

Array.prototype.map()

The map() method is a fun one because it allows you to do something with an Array really fast. Before I get into what that means, let’s see what the method actually looks like:

const newArray = array.map(callback())

The map() method takes a callback function just like filter() does. The difference between the two is that map() will create a new Array that has the same amount of items as the original Array, whereas with filter() you can end up with a smaller Array.

So why is it fun? In the case of the inventors we spoke of above, let’s say we want to have an Array with the full names of all of the inventors. We can use map() to do that:

const fullNames = inventors.map(inventor => (
`${inventor.first} ${inventor.last}`
));

Here’s what’s going on:

  1. Just like filter() we pass a callback function which takes the inventor as an argument. The function will be called for each inventor.
  2. We then implicitly return a template literal with the inventor’s first- and lastname separated by a space.
  3. The new Array const fullNames now holds all of the full names.

If you want to know more about the map() method, go check out MDN.

Array.prototype.sort()

With the sort() method we can, as you might have guessed from the name, sort an Array. The method takes a callback function that takes two arguments which you’ll compare to figure out how to sort them out. You then come up with a condition that returns 1 or -1. Returning 1 moves the argument up in the new array while returning -1 moves the argument down in the new array. Let’s first look at the actual method:

const newArray = array.sort(callback(a, b))

This time we want to sort the inventors based upon their birthdate. So the oldest would go on top and the youngest at the bottom:

const ordered = inventors.sort(function(a, b) {
if(a.year > b.year) {
return 1;
} else {
return -1;
}
});

Here’s what’s going on:

  1. Just like filter() and map() we pass a callback function, but this time the function takes two arguments we simply call a and b. The method will pass the function two inventors to compare until it’s done sorting.
  2. We compare the arguments using an if statement that simply checks if the year a was born in is greater than that of b and if it is it will return 1, thus moving that inventor up in the Array. If it’s not it will return -1, moving the inventor down in the Array.
  3. The new Array const ordered now holds a list of the inventors sorted by the year they were born in.

Something that is very cool to use if you like single line methods, is a ternary operator. It’s a shortcut to the if statement and it looks like this:

condition ? expr1 : expr2

Instead of writing out what happens, the actual if statement might be a little clearer:

if(condition) {
expr1
} else {
expr2
}

So if the condition is true it will run ? if it’s not it will run : .

With the ternary operator in mind we can turn the entire method into a single line arrow function using an implicit return:

const ordered = inventors.sort((a, b) => a.year > b.year ? 1 : -1);

Pretty cool, right?

If you want to know more about the sort() method, go check out MDN.

Array.prototype.reduce()

When I decided to learn JavaScript I got all these for loop exercises which looked like this:

for (var i, i < 10, i++) {
console.log(i)
};

With it you could do all kinds of cool stuff like figure out the total of all the numbers inside an array:

var array = [1, 2, 3, 4, 5];
var total = 0;
for (var i, i < array.length, i++) {
total += array[i]
};

When the loop finishes the total would then be 15 and you’d be happy because who want’s to do mental math anyway, right? The problem with this approach, however, was that I suddenly had to do and learn all this extra stuff like bracket notation using a variable? What?! It screwed me over for a while and I had no idea what I was doing.

Looking back now I don’t understand what was so hard, but everything’s easy in hindsight.

Okay back to the reduce() method. You see, the story has a purpose because the method is basically a for loop in which you can create a total based on an expression using all the items in your Array. Here’s what it looks like:

const newArray = array.reduce(callback(), inititalValue)

The method takes two arguments: a callback function and an initial value. Although the initial value is optional, it is recommended that you still use one as you could end up with unpredictable results.

So using our inventors one last time, we now want to know how many years all of the inventors combined lived. Here’s how we do it:

const totalYears = inventors.reduce((total, inventor) => {
return total + (inventor.passed - inventor.year);
}, 0);

Here’s what’s going on:

  1. Just like the other methods we pass a callback function and, just like sort(), this method takes two arguments: the total and the next item to be used in the loop (which was var i in our for loop example). Now here’s why the initial value is important. If the callback is being called for the first time, there is no total to be used yet. Instead it will take the initial value as the first total.
  2. We then make a little calculation to figure out how long the specific inventor has lived and add his years lived to the total years lived by all inventors.
  3. When the loop finished we now have a variable const totalYears which holds the combined years the inventors have lived.

We are using an explicit return right now, but we can also use an implicit return like so:

const totalYears = inventors.reduce((total, inventor) => (
total + (inventor.passed - inventor.year)
), 0);

If you want to know more about the reduce() method, go check out MDN.

TIL (Today I Learned)

  • We can make neat and useful oneliners using arrow functions
  • map() and sort() will always return the same amount of items
  • ‘accumulator’ is just a fancy word for ‘total’ in the reduce() method
  • An initial value is pretty important in the reduce() method
  • How 1 and -1 work in the sort() method

Phew, that was a long one. For those who read on until the end, I know it’s a lot of information to take in. To be honest, it was more exhausting to write this article than it was to do the exercise. The amazing thing is; because of the way I write these articles, I also research a couple of extra things to make sure that what I write is as clear as can be. So in addition to the videos I can definitely say I get how these methods work now!

All of my code can be found at GitHub.

Wes is an amazing teacher. If you want to become more comfortable with Javascript, go check out his free course at javascript30.com.

Thanks for reading and until next time!

--

--

Mike Ekkel

Frontend developer from Rotterdam, the Netherlands. Currently @ Bynder. Follow me on twitter @Murkrage.