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