Codementor Events

Which Array Function When?

Published May 08, 2018Last updated Nov 04, 2018
Which Array Function When?

There's a lot of hullaballoo some days about "you should use reduce more" or "you don't need a filter, use a map", or "For? Why not forEach?"

The truth is, Arrays and all of their iterator functions can be confusing for beginners, so I'm going to try and simplify things for everyone by framing the question from the end: what do you want to get back?

Short version

  • Return one thing for each existing thing: map()
  • Return only some of the existing things: filter()
  • Return only one new thing: reduce()
  • Don't return anything, but do something with each existing thing: forEach()

I'll give you a quick rundown of each, followed by examples using the older, non-arrow-function syntax as well as the newer arrow-function syntax.

Return one new entry for every existing entry: map()

If you have an array of values, and you want to do something to each entry in that array and return a new array with the new values, then map() is your friend. Here's a simple function that takes an array and doubles every entry:

const originalArray = [1, 2, 3];
const newArray = originalArray.map(function(item) { return item * 2;
});
console.log(newArray); // -> [2, 4, 6]

Here's the same thing using the newer syntax:

const originalArray = [1, 2, 3];
const newArray = originalArray.map(item => item * 2);
console.log(newArray); // -> [2, 4, 6]

Notice that, with the newer arrow syntax, we don't have to use the function keyword, the return keyword, or curly brackets. That's because arrow functions give us an implicit return for 'simple' functions like this one. You can read more about arrow functions here, from Wes Bos.

Return a new array with only some of the existing entries: filter()

Filter is probably the easiest array function to understand, because it is so well-named. Filter takes an array of values, performs a function or comparison on each value, and then returns a new array of just the values that pass it's test (what we call 'truthy' values).

Here's an example that takes an array of numbers and returns just the ones that are larger than 5:

const originalArray = [1, 9, 4, 2, 42];
const newArray = originalArray.filter(function(item) { return item > 5;
});
console.log(newArray); // -> [9, 42]

Here's the filter part with an arrow function:

const newArray = originalArray.filter(item => item > 5);

Return one new thing only: reduce()

Sometimes you have an array of values and just want to return one new thing from them. Reduce takes an array, performs a function or comparison on each item, and then does something to what's called an 'accumulator'. This is one of those functions that's actually easier to describe with an example, because the terms one has to use to describe it are just as confusing as the function itself!

Suppose you have an array of names, and you want to count the number of times the name 'Bob' shows up:

const originalArray = ["Alice", "Bob", "Charlie", "Bob", "Bob", "Charlie"];
const numberOfBobs = originalArray.reduce(function(accumulator, item) { if (item === "Bob") { return accumulator + 1; } else { return accumulator; }
}, 0);
console.log(numberOfBobs); // -> 3

Again with arrows:

const numberOfBobs = originalArray.reduce((accumulator, item) => { if (item === "Bob") { return accumulator + 1; } else { return accumulator; }
}, 0);

As you can see, the arrow function didn't save us as much typing this time, because we had to provide two parameters to the function and then had logic before we could return, so we still needed curly brackets.

The 0 at the end of the reduce function is the value we start off the accumulator with, adding 1 to it if the value we encounter is "Bob", otherwise we return the accumulator as it currently is. If you don't return anything, then the next time the function is run the accumulator will be undefined.

Do something with each array value but don't return anything: forEach()

Sometimes you'll have an array of values that you want to do something with, but don't need to keep track of what the return is from each function call. This is what forEach() is for.

const originalArray = [1, 2, 3];
originalArray.forEach(function(item) { doSomething(item);
});

And again with arrows:

originalArray.forEach( item => doSomething(item); );

Final Notes

Simple and sweet. These are the simplest use cases I could come up with for each function to try and make it as easy as possible to understand when you should use each. There is a huge amount of tasks you can do with these functions, and there is an 'advanced' form of each of these functions that gives you the current index too:

arr.map((item, index) => {})
arr.filter((item, index) => {})
arr.reduce((accumulator, item, index) => {})
arr.forEach((item, index) => {})

If you need it, use it!

Discover and read more posts from Andrew Steele
get started
post comments1Reply
George Jempty
7 years ago

Going a little deeper, sometimes it’s good to know when not to use (one of) these. Take forEach – you cannot use break within it, so if you need to exit your loop early, use a “traditional” for-loop (same goes for continue)