The map
function came up at the meetup today and I thought a quick explanation of when one might use map
, filter
, and reduce
might be useful to people who don’t use them regularly yet.
Map
If you have a collection of things (an array) and want another array of equal length, where some or all of the items are changed, then you might want to use map
.
The difference between map
and forEach
is that map
returns an array of equal length and forEach
returns undefined
. If you aren’t going to do anything with the result, you can use forEach
, but otherwise, you can use map
.
Here are a few examples, using ES5:
Doing something to every number in a list
Here’s an example that multiplies every number in an array by itself. map
returns a new array and doesn’t modify the original.
var arr = [1, 2, 3, 4, 5];
var newArr = arr.map(function (item) {
return item * item;
});
Doing something to every string in a list
Plucking a value from an array of objects
If you have an array of objects and want to pluck some information out of each item, you can use map
.
Filter
If you have an array and want to remove some of the items, then you might be looking for filter
.
Filter out invalid values
Filter out numbers less than 10
Reduce
If you have an array and want to turn them into one value (for example, summing an array of numbers), you can use reduce
.
reduce
has many other uses, but there are longer tutorials about it that could explain it better. The main tip here is that if you have a collection of things (an array in JS) and want to turn them into one value, you might be looking for reduce
.
Summary
A quick guideline:
Starting Point | Desired Result | Function |
---|---|---|
An array | A new array of equal length | map |
An array | A new array of equal or lesser length | filter |
An array | A single value (which can be an array) | reduce |
An array | Do something with each item but discard the result | forEach |
A good exercise is to try to write filter
and map
functions while only using reduce
.
If anyone has other quick tips on when to use those functions, leave a comment below.