Stephen Sun

Software engineer based in Houston, Texas.

I'm a detail-oriented individual who thrives in fast-paced team environments. I have experience across different industries, working with both front end and back end technologies.

Chaining Array Methods

Link to code snippet: GitHub

One of the greatest things about JavaScript is how easy it is to work with arrays. The various array methods (map, filter, reduce, etc.) can be combined with arrow function expressions to create succinct code.

In addition, we're able to combine or chain these specific array methods to perform different operations sequentially.

Set the Scene

Let's start with an array of different vehicles. Each vehicle will have a type, brand, color, and a price.

const vehicles = [
  { type: 'car', brand: 'Tesla', color: 'red', price: 50000 },
  { type: 'car', brand: 'Toyota', color: 'blue', price: 20000 },
  { type: 'truck', brand: 'Ford', color: 'green', price: 40000 },
  { type: 'SUV', brand: 'Nissan', color: 'beige', price: 35000 },
  { type: 'car', brand: 'Tesla', color: 'gray', price: 80000 }
]

Now, let's say we want to find out which cars cost more than $20,000 from least to greatest in price. Breaking the requirements down into steps, we would get the following:

  1. Filter vehicles by type car
  2. Filter cars by prices higher than $20,000
  3. Sort cars from least to greatest
  4. Print out each car and its corresponding price

Filter, Sort, and Map

For the first step, we'll need to get just the vehicles that are cars. We can combine this with our price requirement using one Array.filter() method.

If we had stopped here, we would get the two Tesla cars, but they may not be in the correct order. To ensure that the cars are ordered from least to greatest by price, we need to apply the Array.sort() method.

This can be done through chaining. Because Array.filter() returns an array, we can chain the sort method, which will be applied to the result of the previous filter method.

vehicles
  .filter(vehicle => vehicle.type === 'car' && vehicle.price > 20000)
  .sort((vehicle1, vehicle2) => vehicle1.price - vehicle2.price)
  .map(vehicle =>
    console.log(
      `${vehicle.color} ${vehicle.brand} ${
        vehicle.type
      } is $${vehicle.price.toFixed(2)}`
    )
  )

Now that we have the desired outcome that we were looking for, it's time to print the result to the console. We can conveniently print out each element in our final array using Array.map().

// red Tesla car is $50000.00
// gray Tesla car is $80000.00

Template literals can be used to format the text as we choose, using property values from the elements in the array.