Thursday, December 7, 2017

Map, Filter and Reduce In Javascript

map creates a new array by transforming every element in an array, individually.
filter creates a new array by removing elements that don't belong.
reduce, on the other hand, takes all of the elements in an array, and reduces them into a single value.

Suppose we have an app that maintains an array of your tasks for the day. Each task is an object, each with a name and duration property:
// Durations are in minutes
var tasks = [ 
    'name'     : 'Write for Envato Tuts+', 
    'duration' : 120 
    'name'     : 'Work out', 
    'duration' : 60 
    'name'     : 'Procrastinate on Duolingo', 
    'duration' : 240 

map in Practice

When we need to iterate over an array – we can use forEach.
When we need to iterate and return the data for each element – we can use map.

Map calls the function for each element of the array and returns the array of results. Let's say we want to create a new array with just the name of each task, so we can take a look at everything we've gotten done today.

Using map, we can write:
var task_names = (task, index, array) { 

// Using ES6 arrow functions
 var task_names = => );

//Output: [{ 'name' : 'Write for Envato Tuts+' } , { 'name' : 'Work out' }, {'name' : 'Procrastinate on Duolingo'}]
Arrow functions let us leave out the return keyword in one-liners.

filter in Practice

The next of our array operations is filter. It takes an array, and filters out unwanted elements. Let's revisit our task example. Instead of pulling out the names of each task, let's say I want to get a list of just the tasks that took me two hours or more to get done.

Using filter, we can write:
var difficult_tasks = tasks.filter(function (task) {
    return task.duration >= 120;
// Using ES6 arrow functions
var difficult_tasks = tasks.filter((task) => task.duration >= 120 );

//Output: [{ 'name' : 'Write for Envato Tuts+', 'duration' : 120  }, {'name' : 'Procrastinate on Duolingo', 'duration' : 240}]

reduce in Practice

Let's turn back to our tasks example. What If we wanted to know the total amount of time we spent working today?

With reduce, that becomes:
var total_time = 0;

var total_time = tasks.reduce(function (previous, current) {
    return previous + current.duration;
}, 0);
// Using ES6 arrow functions
var total_time = tasks.reduce((previous, current) previous + current.duration );

//output: 420

In this tutorial, you've learned how map, filter, and reduce work; how to use them; and roughly how they're implemented.

For detailed explanation, visit How to Use Map, Filter, & Reduce in JavaScript