Chaining of Array Methods in JavaScript
There are some methods in JavaScript that can loop through the array. We already have a knowledge about these array methods.
- Filter method ( filter())
- Map method ( map())
- Reduce method ( reduce())
- Find method ( find())
- Sort method ( sort())
We will learn how to chain all the array methods together.
Example:
const products = [
{ 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.
- Filter those elements whose price is greater than 100 using filter() method.
- Map those elements to a new array with a new sale price(50% off).
Example:
<script>
const products = [
{ name: 'dress' , price: 600 },
{ name: 'cream' , price: 60 },
{ name: 'book' , price: 200 },
{ name: 'bottle' , price: 50 },
{ name: 'bedsheet' , price: 350 }
];
const filtered = products.filter(
product => product.price > 100 );
const sale = filtered.map(product => {
return `the ${product.name} is
${product.price / 2 } rupees`;
});
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 }
];
const sale = products
.filter(product => product.price > 100)
.map(product => `the ${product.name}
is ${product.price / 2} rupees`);
document.write(sale);
</script>
|
Output:
Conclusion:
- 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.
- Since the filter method returns an array we can chain it to the map method which works on an array and vice-versa.
- This process can be applied to all the array methods which makes the code concise.
- 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
Share your thoughts in the comments
Please Login to comment...