Map, Filter and Reduce

In this article, We’ll see about map, filter and reduce function and discuss them one by one and understand their use cases.




map: applies a function to all the items in an input list.

filter: creates a list of elements for which a function returns true.

reduce: is a performing some computation on a list and returning the result.

let’s see an example of map, filter, reduce

  const sales = [2000, 2500, 3000, 1500, 1000];

We’ve a sales’s array which contains a sale amount.

We’ll understand filter, map, reduce using perform different different action.

We’ll calculate the total sales.

We’ll get the all sales which is >= 1000.

We’ll calculate the 10% commission of that sale which is >= 1000.

// we'll use reduce method to get total sales

const sales = [2000, 500, 750, 2500, 3000, 1500, 1000];
var totalSales = sales.reduce((pos, cur) => pos + cur);
console.log(`Total Sale: ${totalSales}`); // Total Sale: 11250

// we'll use filter method to all sales which is >= 1000

var filterSales = sales.filter(sale => sale >= 1000);
console.log(filterSales); // [2000, 2500, 3000, 1500, 1000]

// we'll use map method to get 10% commission of that sale which is >= 1000

var earnCommission = filterSales.map(sale => sale / 100 * 10);
console.log(earnCommission); // [200, 250, 300, 150, 100]

That’s it!. Please share your thoughts or suggestions in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *