5 Array Methods That You Should Be Using Now

Array "Extras" no more
October 1, 2014

When ECMAScript 5 was published in 3rd Dec' 2009, it brought in additional new set of Array methods that seeks to improve upon the existing one. However, these newfangled array methods did not really catch on as the lack of browser support for ES5 at that time kept developers away.

Array "Extras"

No one doubted the usability of these methods but the effort to write the polyfill for them was not worth it. It became a "good-to-have" instead of being a "must-have". Someone actually coined these methods as Array "Extras". Ouch!

But times are changing. If you sniff around popular open-source JS projects on Github, you find that the trends are shifting. Developers who want to cut bulk (third-party libraries) are relying on native syntax whenever possible.

It's time we start moving forward.

My starting five

Out of the 9 ES5 Array methods, I will be picking 5 methods that I personally deemed the most useful because it is relevant in use cases that are common to developers.

1) indexOf

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

Use Case: Check for any occurence of "orange" in an array.

Without indexOf():

With indexOf():

The brevity explains itself

Now what if I want to return all the results that satisfy a certain criteria?

2) filter

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

Use Case: Find me all the items in the array that have the name "orange"

Without filter():

With filter():

Just like indexof(), you are writing succinct code.

3) forEach()

The forEach() method executes a provided function once per array element.

Use Case: Iterate through an array

Feel your productivity pulsating through your fingers by using `forEach()` today

forEach() is a major upgrade over the for loop. If there's only one method that you can choose, please let it be forEach().

A commonly overlooked problem of using for loop is that the variables declared within the for loop are not local to the loop. These variables are accessible within the same scope the for loop is in and are susceptible to be overwritten.

Note: From jsperf, for loop is actually shown to perform much better than forEach.

In my opinion, I will still use forEach unless I'm iterating through large datasets(>1 million records). Shaving milliseconds shouldn't be a priority over productivity.

4) map()

The map() method creates a new array with the results of calling a provided function on every element in this array.

Use Case: Parse and return a array of objects that contains a additional new property, full_name

Without map():

With map():

map() is now my favourite method to use in javascript-heavy applications which deal with manipulation of server-sent data.

5) reduce()

The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) has to reduce it to a single value.

To be honest, it took me awhile before I started embracing reduce. The concept was abstract to me and the word accumulator was scary. It was until I started a excellent functional javascript series by nodeschool, did I manage to grasp the concept. But still I didn't see much use for it until I was refactoring my code one day and it hit me that reduce() was awesome!

Use Case: Parse the array and return an object that
contains the number of times each string occured in the array

Without reduce():

With reduce():

Allow me to explain reduce() in my own understanding. reduce(callback,initialValue) takes in two parameters, callback function and initialValue. The callback function itself takes in 4 parameters, prev and next, index and array. You just need to know prev and next.

prev refers to the first item in the array while next refers to the second item. But take note that if you pass in a initialValue, that prev will take on that initialValue and next will be the first value of the array.

The passValue function provides a initialValue to `reduce()`

From the above snippet, you see that we are returning a value at every iteration. This value is passed on to the prev parameter of the next iteration. You will get a clearer picture from the next snippet.

Remember to click on "Result" to see the log messages.

Thanks to Webucator, a provider of JavaScript training, for producing this video illustrating the reduce() method:

Demethodizing

These aforementioned methods are only available to Array but they do come in handy for Nodelist, jQuery Objects and even String. To expose these Array methods, we can use this technique call "demethodizing".

Credits to /u/agdcoa and /u/ThetheChad over at /r/javascript

We demethodize the forEach method into a generic function call each using Function.prototype.call.bind. This each function can now be used on objects other than Array.

Browser Support

According to ECMAScript 5 compatibility table, all the above 5 mentioned Array methods are supported in all mobile browsers and in almost all mainstream desktop browsers (I say almost because IE only provides supports for version 9+).

And in any case you will need backward compatibility, I highly recommend underscore.js. Underscore provides a full range of functional helpers that are extremely useful for developers who deals a lot with collection manipulation.

Start Small

If you are still not confident in trying out these methods on your production projects, try refactoring your side projects then. You will learn to love it! I did.

Like this article?
Subscribe below to get first-hand updates!

RSS