JavaScript Array Methods to Make You a Better Developer

Paige Niedringhaus
7 min readApr 30, 2018

--

Back when I began my new career as a web developer, the fact that I could loop through an array of objects in JavaScript was very cool.

The classic for loop, it will always have its place, but there’s a world of other array methods just waiting to be utilized in JavaScript. The right tool for the right job is what I’m constantly trying to keep in mind when solving problems.

Now, having worked at it for almost 2 years, I’ve learned a heck of a lot more, including some much more sophisticated methods for manipulating arrays, which I’d like to share today.

One more thing I’d like to add before diving in, is that, in general, it tends to be a better practice not to alter existing arrays or objects. If you mutate the original item, you run the risk of unforeseen side effects: wherever else in the code that array or object is referenced, the mutated result could be used instead. This can make finding the root cause of a bug caused by the mutated code more difficult than it needs to be, to say the least.

Therefore, the methods I cover are known as pure functions, because instead of changing the original array, they instead make a copy and make the changes to that copy and return it to the scope outside of the method as a new array. Just something to keep in mind as you read through this article.

Map

The first method that will come in extremely handy is Array.map(). The map method takes in an array, and creates a new array with the results of calling a function for every element in that array. It sounds a little complicated but it’s not too bad once you see some examples.

Here’s Array.map() being used on an array of strings:

Above is an example of map looping over each element in the greetings array and producing a new array called sayHelloWorld which has each greeting plus the word ‘world’ added to the end.

And here is Array.map() creating a new array of objects:

This array of objects is used by map to create a new array of objects where the key is the language and the value is the greeting. The original array of objects remains unchanged though.

Filter

Array.filter() is another useful method. It works by creating a new array from the original of all the elements in that array that pass a test implemented by the provided function. Let’s take a look at an example of this.

Check out how Array.filter() works:

The function filteredGreetings() takes in a parameter (a string in this case), and checks through the array of strings to see if that letter exists in the words. If it does, it returns the index in the string in which they exist, and adds them to the new array, and if they don’t it returns -1, and they are not added to the array.

Reduce

The Array.reduce() method is powerful, it can be used in a variety of ways ranging from simple to very complex ways, significantly cutting down on the amount of code needed to achieve results. In essence, reduce takes in an array, applies a function against something called an accumulator (more on that in a second), and each element in the array, and reduces it down to a single value.

Array.reduce() can also accept a second, optional, argument called an initial value, which is simply the first value to use for the first callback of the function, if it’s not supplied, the first value in the array will be used instead.

Now, an accumulator, as the name suggests, accumulates the value returned by the function each time the function’s callback is invoked. Makes total sense, right? If the answer is no, it’s totally fine, read on for a few examples to help clear things up.

Below is a simple example adding up numbers in an array using Array.reduce().

Two examples using Array.reduce() on an array of prices. Both functions take in the same array of numbers and run the same function (adding the accumulator to the current value being iterated over), but the second reduce function also takes in a second parameter of an initial value. This means that before the internal function even runs, the sum2’s value begins at 10 then loops through the rest of the array after that.

This second example counts the number of times the various Avenger super hero names show up in the array. If they’re new to the object being created, their name is added with a count of 1, if they already exist in the object, the count is incremented by 1 each time it’s found.

This is another example of how reduce can be used to count the number of times a particular word is referenced in an array. The same kind of logic could also be used on a string, by simply splitting the string apart on spaces and then reducing through the resulting array and tallying up the words.

For Each

The Array.forEach() method is a cleaner, more elegant version of the OG for loop, but it is not always the right solution. For instance, if you need to loop over an array only until you find something that matches whatever argument it is you’re trying to find and then return, Array.forEach() is not the answer. ForEach will keep going until it has gone through every element in that array. Period. Regardless of what it finds or doesn’t find.

But as long as you need to iterate over every object in an array, and run a function against that item, Array.forEach() is a good choice.

There’s really not a lot of explanation needed for this one. It’s a for loop, only easier to type out, and remember, it won’t stop iterating until it has accessed every element in the array.

Includes & Some & Every

If there is a situation where you just need to know if an array includes a value, at least once, Array.includes(), Array.some() and Array.every() may be the methods you need.

Like the method name indicates, Array.includes() determines whether an array contains some element and returns true or false. If the array includes it more than one time, it won’t indicate it because it will stop iterating as soon as it finds the first item that returns true. Array.includes() can also take a second parameter as an argument: a search index, which specifies where the search of the array should begin according to the index.

Fun fact: Array.includes() was named as such because MooTools had already added a method to the array prototype called Array.contains() which works slightly differently than how Array.includes() works. To avoid breaking all the sites currently employing MooTool’s Array.contains() method, Ecma International decided to rename their array method to Array.includes() instead.

Here’s a simple example of Array.includes() at work:

This function just loops over the array and returns true if the string is contained anywhere within the array.

Array.some() is similar to Array.includes(), but instead of just taking in an array, it takes in both an array and the value or function to evaluate the items in the array against. It will iterate through an array and return true or false based on if it finds what it’s looking for. Also like Array.includes(), Array.some() will end its iteration as soon as it finds a value that will return true.

Check out this example of Array.some():

As you can see, the function someHola, takes two arguments: the array and the value the function is looking for (typeOfHello). Since ‘Hola’ exists, the function returns true.

Every() is like some(), only every element in the array must pass the test for the function to return true. It’s pretty self-explanatory.

Here’s an example of every() in action.

The first function everyHello(), checks the length of all the strings in the greetings array and since they’re all greater than or equal to 4, it returns true. The second function everyHello2(), does the same check but with a length greater than or equal to 6, and it returns false since not all the strings are at least that length.

Sort

Array.sort() is an incredibly useful method, but it is also tricky remembering how it sorts if a compare function is not supplied, which directs Array.sort() on how to compare and arrange data.

Left to its own devices, Array.sort() will convert all elements to strings and compare each element according to its Unicode order (so although “Banana” comes before “cherry”. In a numeric sort, 9 comes before 80, but because numbers are converted to strings, “80” comes before “9” in Unicode order).

In general though, this is a very powerful and useful method, that I use regularly, I just tend to supply a comparator function for sort to use.

Note: This method does modify the original array, but you’re only sorting it, and not directly altering the data, so there’s less chance of this type of change negatively impacting other blocks of code.

Here’s Array.sort() on an array of numbers and on an array of objects.

The first function sorts the numbers array from low to high. The second function sorts the greetings by various countries by their language value (which first converts all the characters to uppercase, lowercase would work too, to eliminate the differences in Unicode caused by upper or lower case letters).

Another nice thing to note, is that many of these methods can be chained together, eliminating the need for extra variables, and making your code cleaner and easier to read and follow.

And that’s it.

These are some of the methods I use most often when working with arrays in JavaScript. If you get good with these, you’ll be able to own arrays and do some very cool things with very few lines of code.

Thanks for reading, and claps are very appreciated!

If you enjoyed reading this, you may also enjoy some of my other blogs:

References:

--

--

Paige Niedringhaus

Staff Software Engineer at Blues, previously a digital marketer. Technical writer & speaker. Co-host of LogRocket & React Round Up podcasts