Find your content:

Search form

You are here

Javascript Filter vs Map vs Reduce - Help Interview Questions

 
Share

Javascript Filter Method

Whenever you have to filter an array, javascript inbuilt method to filter your array
is the right choice to use. Filter let you provide a callback for every element and
returns a filtered array.

Filter executes the callback and check its return value.
If true it includes the data into result array or doesn't include.


var sample = [1,2,3];
var result = sample.filter(function(elem){ return elem != 2});
console.log(result);// [1,3]

In es6
var result = sample.filter(elem => elem != 2);

Note: Filter does not update the existing array.

 

Map

This method executes all the elements in the map and returns the new array.

var sample = [1,2,3];
var mapped = sample.map(function(elem){
return elem * 10;
});

//es6
let mapped = sample.map(elem => elem * 10);
console.log(mapped); //[10, 20, 30]

Reduce

As the name already suggest reduce method of the array object is
used to reduce the array to one single value.

For example if you have to add all the elements of an array you can
do something like this.

var sample = [1,2,3];
var sum = sample.reduce(function(sum, elem){
return sum + elem;
});

in ES6
var sum = sample.reduce((sum, elem) => sum + elem);
console.log(sum); //6

My Block Status

My Block Content