Must Know Array Methods in JavaScript

A guide for JavaScript higher order array functions

Steven Wu
JavaScript in Plain English

--

Photo by Fotis Fotopoulos on Unsplash

One of the major reasons why I love JavaScript (JS) today is because there are some very useful array methods that have been included ever since the introduction of ECMAScript 6(ES6) in 2015. When I first learned JS in I pretty much only used the forEach loop for most of these examples, so today I will show you guys how to use these amazing built in array methods to save you time and resources when coding with JS.

Let’s imagine a customer shopping for some groceries at your local supermarket and you have been hired to program the cash register to manipulate some data from the customer’s grocery cart.

Using that scenario, I will provide some examples of how and when to use these array methods.

Below is today’s example array of a grocery cart containing :

  • Banana| Price: $0.50, Category: fruit, Sale: false
  • Avocado| Price: $2.00, Category: fruit, Sale: false
  • BBQ Chips| Price: $2.00, Category: snack, Sale: true
  • Bread Loaf| Price: $5.00, Category: bakery, Sale: false
  • Milk| Price: $0.50, Category: dairy, Sale: false

.forEach

Starting with the most basic method for today, the forEach method is very simple and easy to use. Great to use for when the cashier rings up the customer’s items and the register needs to display each item back to the customer for confirmation before they pay.

Here’s another example of how to use the forEach loop. Let’s say the customer has a membership at your company and you need to apply a discount for each item that is on sale.

The membersCartTotal function will take a cart and iterate over each item in the cart to check if the item is on sale, if the item is on sale, this function will apply the discount and then add the new sale price to the totalAmount. If the item isn’t on sale, then the regular item price will be added to the totalAmount instead. I also wrote in an else statement just in case of an error and there’s no sale parameter for that item.

.map

bad example of .map usage

The map method is similar to the forEach loop in the sense that it takes an array and iterates over each item to do something but the map method is used specifically to create new arrays. The above example would be “great” if let’s say your company wants to promote healthy living and wants your cash registers to display a little list of healthy items in the customer’s cart, the above example function would be quite inefficient since the array of messages will stay in memory after displaying it to the customer.

Although map and forEach is similar in behavior, programmers needs to code with time and space complexity in mind, so I actually wouldn’t use the map method for the above example since the array of messages will stay in memory just for displaying quick messages to customers.

Below is a better usage of .map. Let’s say your company need to keep track of each item it sells and the price for tax purposes. I would use .map to create a new array of the gross price of each item before I send it to the tax department.

good example of .map usage

.sort

The sort method is used for sorting of course. This JS method creates a new sorted array using two arguments, each representing the items you’re comparing and sorting. In the above example, I built a function to take in the groceriesCart to sort through it, checking each item’s price to see if the first item’s price is lower than the second item’s price and if the price is lower than it goes first or -1 on the index of the array so to speak.

.filter

The filter method takes in an array and iterates over each item and return the item based on certain conditions. Let’s say your company liked the way you coded that sales tax solution and now they want you to build a way to filter out the annual sales list to see how many items were discounted. So for the above example I created a function that takes in the groceriesCart and filter out only if the item is onSale which correctly returned the bbq chips only.

This is a great one to use if you already have some data in place and need to generate a new list based on certain conditions. The filter method is definitely one of my favorites since it’s so powerful and easy to use.

.reduce

Before we get into the reduce method, let’s look at the above example of how we can get the cart total using the basic for loop. We set the starting total at 0 and we iterate over each of the cart items to add the item price to the total and additionally we check to see if the item is on sale as well and return the correct total amount.

While there’s nothing wrong with this code, it’s just a hassle to write a whole indexing for loop for a function as simple as this. So let’s refractor this same function using .reduce instead.

To be honest the reduce method was a little confusing to me at first but once you get the syntax it’ll be a breeze to use. Let’s break it down, this method takes in three arguments:

  • Line: 104 |currentTotal- which is what we are calling the total
  • Line: 104 |item- simple to represent each entry of data in groceriesCart
  • Line: 110 |0 — setting the starting value for currentTotal

The initial value of currentTotal gets initiated with the value of 0, then the .reduce method iterates over each entry to check if the item is on sale or not and then it returns currentTotal with the item price.

Conclusion

There we go! We used the reduce method and saved a few lines of code, which don’t seem like much but your job isn’t building only one function. So, if you think about it, learning these methods will definitely make you a faster and more efficient coder.

Hope you enjoyed this JavaScript article! Please leave a comment if you do and follow for more coding guides.

More content at plainenglish.io

--

--