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

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 = tasks.map(function (task, index, array) { 
    return task.name; 
});

// Using ES6 arrow functions
 var task_names = tasks.map((task) => task.name );

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 );

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 = tasks.reduce(function (previous, current) {
    return previous + current.duration;
}, 0);
 
// Using ES6 arrow functions
var total_time = tasks.reduce((previous, current) previous + current.duration );

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

No comments:

Post a Comment