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!
Latest comments (42)
Wapdam is the new site which offer good movies and web series
Nice to see all the code and the explanations. Really clarifying
WapTrick is very great for games, app, videos and movies
Nice one... Problem solved.
makrospecials.net/zamob/
Good, well educative to read, Thank You
mstwotoes.com/mp3paw-download-free...
I always try to understand the contents of Multivitamins and Supplements been sold in the market before making best choice of what to go for.
Zamob.co.za is one of the largest mobile web portal in South Africa, where mobile users can download lots of android games, videos, mp3 music and java games all for free. You can download millions of free Games, Apps, Music....
If only I would have read this article back then!
I struggled my way to learn about these type of higher order functions with .NET's LINQ and Kotlin's standard library.
But this post is gold. I'll make sure to share it with friends.
Thanks for your thoughts Rafael. This article is aimed at beginners, so I chose the easiest-to-read, more verbose way of expressing things.
Great article dude. Well written and easy to understand. You might want to reference at least once the arrow functions real name is a Lambada function. Can't wait to read more
Thanks Peter. I believe you're referencing lambda expressions, which are expressions which return a function. While it's true that Javascript arrow functions are comprised of a syntax which enable shorter definitions of expressions which return functions, very very few people in the Javascript community refer to these as lambda expressions. Doing so promotes confusion for newer developers more than helping them, as searching for 'Javascript lambda functions' just redirects them back to 'arrow functions'. The official standard also calls them arrow functions, so that's what I went with here.
Thanks for the reply. And the spelling correction 😣 I should have used a real keyboard and not my thumbs. That's good to know that they're officially called arrow functions, I will make note of that for myself. Thanks again,
Pete
Ya, this one is hot:
originalArray.forEach( item => doSomething(item); );
Why forEach, what about for...of and for...in ?
I included forEach here because this article was specifically about the iterator functions built into the Array object. for...of and for...in are super great tools, too, but were out of scope for this article. Will definitely include in the larger piece I'm working on writing. ;)
Thanks! I didn't know about reduce. I prefer to use the most simple and readable for the occasion and the most necessary
Nice article! Everyone seems to forget my two favorite functions though,
some
andevery
If you've ever written something like
If you ever find yourself checking the
length
property afteritems.filter()
, you can likely usesome
orevery
to do the same thing without the array generation penalty.Really nice!!! I'm a Python programmer and didn't know JS has functions like that!! Congrats bro
Glad it's been helpful for so many folks already!
Yes, some of these functions could be reduced (pun intended) to an even smaller and possibly more performant size using
&&
, ternary operators, or++accumulator
instead ofaccumulator + 1
. If you're interested in how to take your code to the next level with some of those refactors, definitely read the other comments here!I intentionally stayed away from some of those 'intermediate level' code 'tricks' for the sake of making these examples as readable as possible. ;)
Do you know if
forEach
is better in term of perf thanfor
?Nice post !
According to this
for
is pretty much always faster thanforEach
, so if performance is more important than concise code (and it usually should be) afor
loop is likely a better choice.Correct, as the
forEach
call will incur a penalty invoking the lambda expression.forEach
could have equivalent performance if the JIT inlines the lamba method body, but it's safe to say always expectforEach
to be a bit slower.