JavaScript Array Methods to Make You a Better Developer
--
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.
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:
And here is Array.map()
creating a new array of objects:
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:
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()
.
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.
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.
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:
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()
:
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.
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.
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:
- Mozilla’s web docs do a great job of explaining and providing examples of all the array methods mentioned above: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
- W3Schools also has very helpful docs when Mozilla gets a little too esoteric for me (plus their Try It Yourself option is great for experimentation): https://www.w3schools.com/jsref/jsref_obj_array.asp