Skip to content

Instantly share code, notes, and snippets.

@theankitgaurav
Created November 4, 2016 16:37
Show Gist options
  • Save theankitgaurav/71fe449b0c5cd58a00696382c9e8fd1b to your computer and use it in GitHub Desktop.
Save theankitgaurav/71fe449b0c5cd58a00696382c9e8fd1b to your computer and use it in GitHub Desktop.
JavaScript Map, Filter, Reduce methods Cheatsheet

map()

Use it when: You want to translate/map all elements in an array to another set of values.

Example: convert Fahrenheit temps to Celsius.

var fahrenheit = [0, 32, 45, 50, 75, 80, 99, 120];

var celcius = fahrenheit.map(function(elem) {
    return Math.round((elem - 32) * 5 / 9);
}); 

// ES6
// fahrenheit.map(elem => Math.round((elem - 32) * 5 / 9));

celcius //  [-18, 0, 7, 10, 24, 27, 37, 49]

filter()

Use it when: You want to remove unwanted elements based on a condition.

Example: remove duplicate elements from an array.

var uniqueArray = array.filter(function(elem, index, array) {
        return array.indexOf(elem) === index;
    }
);

// ES6
// array.filter((elem, index, arr) => arr.indexOf(elem) === index);

reduce()

Use it when: You want to find a cumulative or concatenated value based on elements across the array.

Example: Sum up orbital rocket launches in 2014.

var rockets = [
    { country:'Russia', launches:32 },
    { country:'US', launches:23 },
    { country:'China', launches:16 },
    { country:'Europe(ESA)', launches:7 },
    { country:'India', launches:4 },
    { country:'Japan', launches:3 }
];

var sum = rockets.reduce(function(prevVal, elem) {
    return prevVal + elem.launches;
}, 0);

// ES6
// rockets.reduce((prevVal, elem) => prevVal + elem.launches, 0); 

sum // 85
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment