JavaScript’s built-in map, filter, and reduce array methods are invaluable to a modern JavaScript developer. First introduced in 2011, these methods go way beyond the traditional for loop for traversing an array. They make functional programming and its applications in things like React (hi stateless components!) much, much easier.

Map()

Use map when you want to apply a transformation to all elements in an array.

Let’s say you want to multiply all numbers in an array by 2:

const numbers = [1, 2, 3, 4, 5]
numbers.map(x => x * 2); // [2, 4, 6, 8, 10]

If you want to save the output, you’ll need to create a new variable for it:

const numbers = [1, 2, 3, 4, 5]
const numbersTimesTwo = numbers.map(x => x * 2)
numbersTimesTwo; // [2, 4, 6, 8, 10]

A more real-world example is transforming a list of distances from miles to kilometers:

miles = [1, 5, 10, 75]
miles.map(num => num * 1.609344); // [1.609344, 8.04672, 16.09344, 120.70080000000002]

Actually, let’s clean that up a bit and only output to two decimal places using toFixed(), which returns a string:

miles = [1, 5, 10, 75]
kilometers = miles.map(num => (num * 1.609344).toFixed(2));
kilometers; // ["1.61", "8.05", "16.09", "120.70"]

Filter

Use filter() to remove unwanted elements based on a condition. For example, we could remove numbers greater than or equal to 3 from an array. Only when the expression is true will an element be returned.

const numbers = [1, 2, 3, 4, 5];
numbers.filter(x => x >= 3); // [3, 4, 5]

A more real-world example is to remove duplicates from an array. Here we can be slightly clever. First, filter() actually returns a callback function for each element in an array that is invoked with three arguments: element, index, and array. Second, the built-in array method indexOf returns the first–and only the first–index result of an array.

Therefore, if we filter using indexOf then only one result for each value will be returned.

duplicateNumbers = [1, 1, 2, 3, 4, 4, 5];
duplicateNumbers.filter((elem, index, arr) => arr.indexOf(elem) === index); // [1, 2, 3, 4, 5]

Reduce

Use reduce() to apply a function across an entire array and return a single value.

Under the hood reduce() executes a callback function for each element that contains four arguments: accumulator, currentValue, currentIndex, and array.

Here’s a simple example of summing up each number value in an array:

const numbers = [1, 2, 3, 4, 5];
numbers.reduce((prev, curr) => prev + curr); // 15

There’s much more we can do using all four arguments, so look at the MDN Docs for a complete picture.

Conclusion

It’s hard to imagine not having these three methods given how powerful they are and the conciseness of the code generated. It’s well worth the effort to master all three: you’ll find them cropping up again and again in your code in the future.




Want to improve your JavaScript? I have a list of recommended JavaScript books.