We're live-coding on Twitch! Join us!

Flex Those JavaScript Array Muscles

Sometimes we get so wrapped up in new frameworks, coding styles, and tools we forget to stop and get some of the basics back into our head. This article is going to be about that, we are going to look at some of the available array methods and how we can use these methods to sort, filter and reduce an array to get the outcome we want to use.

To get more into the basics of JavaScript, we also have our Getting Started with JS for Web Development course you can check out!

Introduction

Table of Contents

Before we start looking at the methods, we need a deep understanding of what arrays are in JavaScript.

Well, arrays are a list-like object that include methods for us to perform mutations on them, these methods are in the prototype of any array if you console log any array and open its prototype you will see a huge list like this:

This lists is all the methods you can use in any array to transform it or get values from it. You also need to know that nothing in an array is fixed and can be changed at any time and for this arrays are by definition not immutable, of course, you could choose to make them immutable, but by definition, all arrays can change in contents and length.

Sort and Reverse

I'm going to start with these two because, in my opinion, they are the easiest ones to get to know and use in our daily life, I can not tell you how many times I have used any of these two function in an array.

For these methods we are going to use a simple number array like so:

Essential Reading: Learn React from Scratch! (2019 Edition)
``const array = [1, 8, 3, 5, 9, 7];``

Imagine you were handed this array, but you wanted to show it starting from the lowest number to the highest one. What sort does is sort any array given ascending so in this case, if you did this:

``let sortedArray = array.sort();``

It would return a new array with the values:

``[1, 3, 5, 7, 8, 9]``

This sort method also works with names and string characters so if you would like to alphabetically order an array of names or anything involving strings it would do that without any parameters.

You can also pass one parameter to it, and that parameter is the sorting function, by default what javascript does is this:

``````array.sort((a, b) => {
// a = current item in array
// b = next item in array
return a < b;
});``````

What this function does in concrete is that it goes through every element in the array and sees if the current one is smaller than the next one and in that way organizes your new array. So if you wanted to this backward all you would have to do is see if the current item is bigger than the next one, like so:

``````array.sort((a, b) => {
return a > b;
});

// [9, 8, 7, 5, 3, 1]``````

There is also another way to reverse an array, and this is where the reverse function comes in, all this function does is reverse the order of an array, so instead, we can do this:

``````array.sort().reverse();

// [9, 8, 7, 5, 3, 1]``````

And it is the same as what we did above in the function we passed inside the sort. This function doesn't take any parameters and what you see is what you get.

.filter() the Array

After we saw sort and reverse it's time to learn how to filter an array using filter and for this exercise and the ones after this one we are going to use the following array of people:

``````const people = [
{
name: 'Sara',
age: 25,
gender: 'f',
us: true
},
{
name: 'Mike',
age: 18,
gender: 'm',
us: false,
},
{
name: 'Peter',
age: 17,
gender: 'm',
us: false,
},
{
name: 'Ricky',
age: 27,
gender: 'm',
us: false,
},
{
name: 'Martha',
age: 20,
gender: 'f',
us: true
}
];``````

Having this array imagine you only wanted to get the women in here. Basically what you wanted to do is filter this array and only get the people that have the gender key equal to f.

As you can see I used the word filter a lot because that is exacly the function we are going to use in order to get this new array of elements. The filter function takes one argument and that argument is the function we want to run for each element in the array.

This function we pass into the filter also takes one argument and that one is the current element of the array the filter is in.

Get the Women

To use this to get the women we would do something like this:

``````// Filter every element of this array
let women = people.filter(function(person) {
// only return the objects that have the key gender equal to f
return person.gender === 'f';
});``````

We can actually improve this a lot using ES6 and arrow functions:

``let women = people.filter((person) => person.gender === 'f');``

We are missing the return because when using arrow functions in one line javascript will assume you want to return whatever is in that line.

Cool tip: In cases like this you can use `console.table` instead of `console.log` to get a table as the output instead of getting the object references.

So if you head over to the console and console.table this we will get the following:

Getting People Old Enough to Drink

Now to get into something a little more tricky using filter, imagine you only want to return the people who are old enough to drink, and this defers whether you are from the US or not, for simplicity sake let's assume everyone outside the US has a legal drinking age of 18, in this case we first need to check if the person is in the US or not and then either return people who are older then 21 or if they are not from the US return anyone older than 18.

For this we need a small if statement that will check if the person is in the US or not and return it according to it, like so:

``````let legal = people.filter((person) => {
// If the person in the US only return it if they are older or 21
// If not return the person if the are 18 or above
return person.us ? person.age >= 21 : person.age >= 18;
});``````

If you now console.table the legal variable you will see this:

As you can see by these two small examples the filter function is really handy for filtering arrays only to get the results you actually want the user to see, this can be very handy when handling website filters.

.map() the Array

We already created an array that only has the people who have the legal age to drink but wouldn't it be better to add legal as a key of every object and set it to true or false?

This type of transformation is what the map function does, it runs a function for every element in the array we give it and it returns our new array.

In this case, half our work is already done, all this function needs to do is the same conditional statement we just ran in the filter function, the only change it needs to have is get a parameter that will be the object, so we need a function like this:

``let legalFunction = (person) => person.us ? person.age >= 21 : person.age >= 18;``

This function either returns true or false depending on the location of the person. Let's move on to the map function and run this `legalFunction` everytime map loops the array we give it:

``````let legalFunction = (person) => person.us ? person.age >= 21 : person.age >= 18;

let legalIncluded = people.map((person) => {
// set the new legal key equal to the return of the function we just set
person.legal = legalfunction(person);

// return this person but with the legal key added
return person;
});``````

Again if we `console.table()` this we get:

If you check, all the values are correct and our new array has all the information we need. This is of course a simple example of what the map function actually does, if you can run a function for every element in an array you can literally do anything, so if you wanted add 10 years to each person you could simply do:

``````let increaseAge = people.map((person) => {
// set the age key equal it plus 10
person.age = person.age + 10;
return person;
});``````

In my opnion map is the most flexible transform function you have because of how it allows you to change every element and also add or remove keys with great ease.

.reduce() the Array

In all these cases we started and ended with the same array structure, we may have added or changed the elements inside it but the structure was still the same and sometimes this doesn't cut it.

Sometimes we need information from an array and transform it into a completly diffrent array, an object or even a number. Let's say we want to get all the combined ages of the people in the array, there is no way we could do this with how it's structured, this needs to be a number and not an array.

This is where reduce stands out, it allows you to return a whole new element, this function also takes two arguments, the first one is the function we want to run inside the reduce and the second argument is what we want to start with, bascially our starting structure.

The function inside the reduce also takes two parameters, the starter (in this case the number 0) and the current element we are looping through. If you see a reduce function it should look something like this:

``````// the two parameters in the function are the 0 and the person we are in
let age = people.reduce((starter, person) => {
// return something to add to the starter
}, 0);``````

Having these in mind what we really want to do is add the age of the current person the starter of 0 everytime we loop through the array, so what we need is this.:

``````let age = people.reduce((starter, person) => {
// add the person age to the starter
// As it loops t
return starter + person.age;
}, 0);

// This will return 107``````

As simple as this example may be it shows us the power of the reduce, in here we got a huge array and changed in such a way that in the end all we had was the number 107. This means you can start with anything, let's use this in order to create an object like this:

``{men: 3, woman: 2}``

So if we want to build this we need to start with an object that has two keys, one for woman and one for man that both have the value of 0 and from there we need to see what the gender of the person is and increase the correct key. That would look something like:

``````let obj = people.reduce((starter, person) => {
// check if the person is male, if it is increment the value in the starter object with the men key
// if not do that for the woman key
person.gender === 'm' ? starter.men++ : starter.woman++;

// return the modified starter
return starter;
}, {men: 0, woman: 0}); // our starter structure and values``````

if we console.log this we will get: `{men: 3, woman: 2}` as we would expect. In these cases where you want some data and you want to change the structure of it to return something completly diffrent from what you received in the beggining the reduce function is the way to go.

Other Important Array Methods

While `.filter()`, `.map()`, and `.reduce()` are some of the more commonly used, there are many more:

• `.forEach()`: Do something for each item in the array
• `.find()`: Like filter but only returns a single item
• `.push()`: Add new elements to the end of the array
• `.pop()`: Removes the last element of an array
• `.join()`: Join the elements of an array into a string
• `.concat()`: Join two or more arrays (returns a copy)

To find all the methods, check out the reference on w3schools.

Conclusion

This all I have for you today when it comes to array manipulation and transformation. There is a lot more methods we can cover when it comes to arrays and changing them to fit our needs if you would like a second part here let me know in the comments. In the meantime I hoped this article got you back to the basics of learning the language or if you are just learning it now I hope you got a good grasp on how to modify arrays to fit your everyday needs.

Like this article? Follow @NikkitaFTW on Twitter