Open In App

Chaining of Array Methods in JavaScript

Improve
Improve
Like Article
Like
Save
Share
Report

There are some methods in JavaScript that can loop through the array. We already have a knowledge about these array methods.

  1. Filter method ( filter())
  2. Map method ( map())
  3. Reduce method ( reduce())
  4. Find method ( find())
  5. Sort method ( sort())

We will learn how to chain all the array methods together.

Example:




const products = [
  
    // Here we create an object and each
    // object has a name and a price
    { name: 'dress', price: 600 },
    { name: 'cream', price: 60 },
    { name: 'book', price: 200 },
    { name: 'bottle', price: 50 },
    { name: 'bedsheet', price: 350 }
];


We want to do two things.

  1. Filter those elements whose price is greater than 100 using filter() method.
  2. Map those elements to a new array with a new sale price(50% off).

Example:




<script>
    const products = [
  
        // Here we create an object and each
        // object has a name and a price
        { name: 'dress', price: 600 },
        { name: 'cream', price: 60 },
        { name: 'book', price: 200 },
        { name: 'bottle', price: 50 },
        { name: 'bedsheet', price: 350 }
    ];
  
    // Filters the elements with 
    // price above 100
    const filtered = products.filter(
        product => product.price > 100);
  
    const sale = filtered.map(product => {
        return `the ${product.name} is 
        ${product.price / 2} rupees`;
    });
  
    // log the sale price to console
    console.log(sale);
</script>


Output:

A quicker way to achieve this is by using array method chaining. All the array methods work on arrays and return arrays. So we can easily chain these methods.

Example:




<script>
    const products = [
        { name: 'dress', price: 600 },
        { name: 'cream', price: 60 },
        { name: 'book', price: 200 },
        { name: 'bottle', price: 50 },
        { name: 'bedsheet', price: 350 }
    ];
  
    // Writing the different array methods
    // on different lines increases the
    // readability
    const sale = products
        .filter(product => product.price > 100)
        .map(product => `the ${product.name} 
            is ${product.price / 2} rupees`);
  
    document.write(sale);
</script>


Output:

Conclusion:

  1. The output in both the cases remains same. The second method is called chaining of array methods which makes the code a little more concise.
  2. Since the filter method returns an array we can chain it to the map method which works on an array and vice-versa.
  3. This process can be applied to all the array methods which makes the code concise.
  4. This method is not only applicable for arrays, but we can use them on strings also, as long as the methods return and work on strings. The same principle will be applied.


Last Updated : 09 Jul, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads