Sunday, November 18, 2018

Learn to Chain Map, Filter, and Reduce Method In Javascript

This tutorial explains how to chain Map, Filter, and Reduce Method In Javascript. You may have seen method chaining examples in Jquery, java etc programming language. Since all three are called on arrays and since map() and filter() both return arrays, we can easily chain our calls.

Learn to Chain Map, Filter, and Reduce Method In Javascript


Lets see the below example, which will help you to build more understanding on Chain Map, Filter, and Reduce Method In Javascript.

Consider that we are having below data :
var arr = [
  { id: 1, name: 'Android', score : 20, bonus : 15 },
  { id: 2, name: 'Php', score : 10, bonus : 25 },
  { id: 3, name: 'React', score : 40, bonus : 45 },
  { id: 4, name: 'React Native', score : 30, bonus : 25 }
];

The main aim to extract data from array in below order :
1. Extract the name field value whose length is greater that three.
2. once you have extracted data, sum of the score and bonus element of each array items.
3. calculate the sum of result extracted from above array(step-2)

Using chaining concept we will extract the result at a once and final result will be the sum of score and bonus element.
var arr = [
  { id: 1, name: 'Android', score : 20, bonus : 15 },
  { id: 2, name: 'Php', score : 10, bonus : 25 },
  { id: 3, name: 'React', score : 40, bonus : 45 },
  { id: 4, name: 'React Native', score : 30, bonus : 25 }
];

const totalScore = arr
  .filter(newarr =>newarr.name.length > 3)
  .map(arrnew => arrnew.score + arrnew.bonus)
  .reduce((acc, newscore) => acc + newscore, 0);

console.log(totalScore)

Output:
------------------
> 175

This is all about Chain Map, Filter, and Reduce Method In Javascript. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.


No comments:

Post a Comment