DEV Community

Tanner Kirkpatrick
Tanner Kirkpatrick

Posted on

5 JavaScript Array Methods to make your code lean and mean

One of the most important aspects of programming in JavaScript is learning how to manipulate data within arrays. The good ol "for loop" is a tried and true way to iterate through an array, but there are much easier, cleaner, and more efficient ways to handle the same data. Still iterating through arrays only using the for loop? Totally fine. It is important to understand what's going on under the hood, but once you have a firm grasp on the foundational for loop, I strongly recommend moving onto these array methods. There are many different array methods, but I will be covering 5 different methods that you will likely see and use often. Let's take a look.
Note: I will use both es6 and pre-es6 syntax, in order to show the differences and to offer a better understanding of the methods themselves.

Sample dataset for demonstration purposes:
Alt Text

1. map()

The map method is one of the most frequently used array methods out there. In short, the map method returns a new array with whatever values specified by the developer. For example, if we wanted to only grab the names of the items from the items array, we can use the map method. Let's see how it works.

Without array methods like map, we would have to do something like this: Alt Text

Does it work? Sure. But there are much cleaner ways to achieve the same result! In the long run, this saves time, memory, and enhances the readability of your code, which is beneficial for everyone involved.

Pre-ES6 Syntax: Alt Text

So what's going on here? We are declaring a variable called "itemNames" and inside of it is where all of the magic happens. All you have to do is take the name of the array, tack a .map() method onto it, and pass in a callback function as an argument. The callback function also takes a parameter, and this can be named whatever you like. In this case, it made sense to use the word "item" for iterating through our items array. Since we want the names of the items, we are simply returning item.name. This will create a brand new array (which can now be accessed by using the "itemNames" variable) containing the names of the items.

Output:

Alt Text

Let's break this down even more.

ES6 syntax: Alt Text

Thanks to ES6, we can consolidate this into ONE single line of code and achieve the same result. Pretty cool. Okay, so that's great, but what's going on here? Since we are using an ES6 arrow function and there is only one expression being executed in the callback function, we are able to eliminate the curly braces and even the return keyword(implicit return).

2. forEach()

forEach is a bit different in that it does not return an array like map, filter, etc. So what does forEach do? When an anonymous or callback function is passed to the forEach method, it will execute that function for every item in the array. You can also pass in the index of the array item, and even the entire array itself. For this use case, we want to iterate through the items array, and console.log the item name and which position it is in. We can achieve this with a forEach method. Alt Text

Output: Alt Text

Let's clean this up a little bit with some ES6 syntax.
Alt Text

Arrow functions are your friend!

3. filter()

The filter method is one that you will grow to absolutely love. Throughout your development career, there will be many use cases where you will want only certain items in an existing array, and filter is the way you can execute that. Just like map, the filter method returns an array. However, the new array is constructed by conditionals set by the developer. Say we wanted to remove items from the array that are over $150: Alt Text

Output: Alt Text

So on every iteration, the filter method is looking at the price of each item, and if the conditional is met (if the price is less than or equal to 150), the item stays, if not, the item is tossed from the array.

Let's clean it up with ES6 syntax: Alt Text

4. reduce()

This can be a tricky method to learn at first, but once the concept solidifies, it is extremely useful. Imagine we want to add up the prices of our items to get an idea of how much all of our assets are worth. We can use the reduce() method to "reduce" the prices in the array to one single value. Let's take a look:
Alt Text

Now, the callback function in a reduce method normally takes two parameters. One is the accumulator, and the other is the current value. In this example, they are represented as "a" and "c". So essentially, on every iteration, the current value is being added to the accumulator (accumulator is set to 0 by passing 0 as a second argument to the reduce method), and then ultimately returned as one single value.

Output: Alt Text

It is important to note that if an initial value is not provided for the accumulator, it will default to the value of the first index of the array.

Let's clean this up.
Alt Text
Less code, same results.

5. find()

For the 5th and final method, let's talk about find(). Find is a super simple, yet useful method. Essentially, it scans the array and returns the first object that meets certain criteria. For example, if we wanted to isolate the object containing the "TV" item, we would write our code like this.

Alt Text

Output: Alt Text

And of course, let's clean it up with ES6:
Alt Text

Conclusion

There are many different array methods out there to dry out your code and simplify your life as a developer, so take advantage of them! There's no better feeling than converting a clunky for loop into an efficient one-liner. I hope this helped solidify some of the foundational concepts of array methods and ES6 syntax. Stay well and keep coding!

Top comments (1)

Collapse
 
frontendengineer profile image
Let's Code

Working with an array of data is one of my favorite aspect on programming. Transforming, filtering, reducing, etc is a joy to do.

One request, can you make the code accessible so different folks can prolly copy/paste code instead of screenshots?

With good intentions like you, I just created a youtube channel 4 months ago hoping to help someone. Please check it out some of my video regarding array map, filter and reduce when you have time.
youtube.com/channel/UCFIwa5Eqf4kN1...