DEV Community

Which Array Function When?

Andrew Steele on August 08, 2017

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 ...
Collapse
 
erickjth profile image
Erick Torres • Edited

Liquid syntax error: 'raw' tag was never closed

Collapse
 
22samuelk profile image
Samuel • Edited

While using && to actually return the latter is indeed a cool trick, it's probably confusing for beginners. And in my opinion the ternary operator comes in more handy in this case.

Here's a simple approach which uses the ternary operator and should also be pretty easy to understand for beginners:

const originalArray = ['Alice', 'Bob', 'Charlie', 'Bob', 'Bob', 'Charlie']

const numberOfBobs = originalArray.reduce(
  (acc, item) => item === "Bob" ? acc + 1 : acc,
  0
)

That works, because

if (item === 'Bob') {
  return acc + 1
} else {
  return acc
}

is basically the same as

return item === 'Bob' ? acc + 1 : acc

(Think of ? and : as 'then' and 'else')

And since we can leave away the curly braces in this case (since it's just one expression), we can simply use this arrow function:

(acc, item) => item === 'Bob' ? acc + 1 : acc

So this was a brief explanation (hopefully someone understands what I'm saying) of the ternary operator, see MDN to learn more

Collapse
 
22samuelk profile image
Samuel • Edited

I'll just briefly explain what that && does, for everyone not understanding what you mean:

&& returns the value of the right-hand expression when both are truthy.

Same with ||: It returns the left-hand expression if it's truthy, or the right-hand one of the first one was falsey.

See the descriptions of the logical operators (and the examples) on MDN for more information.

So && can be used like 'when the left expression is truthy, return the right-hand (or run a function)'.

E.g.

condition && doThis()

And || can be used to provide a default value (or also run a function or something).

someVariable = someVariable || 0
someVariable || varIsFalsey()

Hope this was not too confusing.

Collapse
 
belethcz profile image
Jaromír Franek

If i would ever seen such code i would instantly decline any pull request this may be contained in.
Do you seriously mean that it make it simpler in any way? I have been programing node.js apps for a 3 years now and seen some horrible things done in sake of simplicity and performance and this may be one of those. What if acumulator have started as -1 for some reason? You would have never change it in the end.

Collapse
 
michie1 profile image
michie1

I understand how the ternary and the logical operators work, and still I agree with you that it doesn't make it "simpler". If and else takes some more lines of code, but it's more easy to debug, refactor, document compared to single line expressions.

Collapse
 
erickjth profile image
Erick Torres • Edited

You are right, when accumulator stars in -1, it'll fail. When I said much simpler, I meant simpler in terms of writing code. :D

Thread Thread
 
billbarron profile image
Bill Barron

Protip: Don't try to be clever with your code:

simplethread.com/dont-be-clever/

Collapse
 
seth10 profile image
Seth T

Has no one mentioned filter!?

const originalArray = ["Alice", "Bob", "Charlie", "Bob", "Bob", "Charlie"];
const numberOfBobs = originalArray.filter(name => name === "Bob").length;
console.log(numberOfBobs); // -> 3

I think a better example of reduce would be something that can't be done with filter.

Collapse
 
yunoctry profile image
Yun

return (accumulator += (item === "Bob" ?1:0));

this way(using "?:" or "&&||" after equal sign) works better in lots of situation

Collapse
 
22samuelk profile image
Samuel

That = in += is redundant since the reducer only needs to return the new value, not change the old one. I mean, it'll still work, because the correct value is returned, but there's no need in changing the passed-in accumulator.

Collapse
 
stephanmullernl profile image
Stephan Muller

return accumulator + Number(item === "Bob");

Collapse
 
andrew565 profile image
Andrew Steele

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 of accumulator + 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. ;)

Collapse
 
darrenkopp profile image
Darren Kopp

Nice article! Everyone seems to forget my two favorite functions though, some and every

If you've ever written something like

const items= [1, 9, 4, 2, 42];

// checks if any item in the array matches the predicate
var hasAnyBigItems = items.some(item => item > 10));

// checks if every item in the array matches the predicate
var allPositive = items.every(item => item > 0);

If you ever find yourself checking the length property after items.filter(), you can likely use some or every to do the same thing without the array generation penalty.

Collapse
 
leydsonvieira profile image
Leydson Vieira

Really nice!!! I'm a Python programmer and didn't know JS has functions like that!! Congrats bro

Collapse
 
jreinhold profile image
Jeppe Reinhold

Best explanation of reduce I've found to date. awesome!

Collapse
 
jservoire profile image
Johann-S

Do you know if forEach is better in term of perf than for ?

Nice post !

Collapse
 
andrew565 profile image
Andrew Steele

According to this for is pretty much always faster than forEach, so if performance is more important than concise code (and it usually should be) a for loop is likely a better choice.

Collapse
 
darrenkopp profile image
Darren Kopp

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 expect forEach to be a bit slower.

Collapse
 
zepner profile image
Zvi Epner

Ya, this one is hot: originalArray.forEach( item => doSomething(item); );

Collapse
 
itzwonderkid profile image
Agware Gideon

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....

Collapse
 
petecapecod profile image
Peter Cruckshank

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

Collapse
 
andrew565 profile image
Andrew Steele

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.

Collapse
 
petecapecod profile image
Peter Cruckshank

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

Collapse
 
cardbelt profile image
CardBelt

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.

Collapse
 
chrisvasqm profile image
Christian Vasquez • Edited

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.

Collapse
 
vaidotas profile image
Vaidotas Piekus

This is great! As a beginner I am always confused between the Filter/Map/Reduce, it is super helpful to have this! Thank you

Collapse
 
gregorgonzalez profile image
Gregor Gonzalez

Thanks! I didn't know about reduce. I prefer to use the most simple and readable for the occasion and the most necessary

Collapse
 
hultberg profile image
Edvin Hultberg

Why forEach, what about for...of and for...in ?

Collapse
 
andrew565 profile image
Andrew Steele

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

Collapse
 
computistic profile image
Hannan Ali

Well arrow functions still save us some code in case reduce.

const numberOfBobs = originalArray.reduce((accumulator, item) => (
  item === 'Bob' ? accumulator + 1 : accumulator
);
Collapse
 
victoriaonu23 profile image
Victoriaonu23

Wow.. i learnt something new today. Always some innovative methods on this space

Collapse
 
yaphi1 profile image
Yaphi Berhanu

This is some of the clearest JavaScript writing I've seen.

Collapse
 
serener profile image
Seren

FouMovies Is one of the greatest movies and tv series website.

Collapse
 
stanleyraymon21 profile image
Stanley Raymond

Nice one... Problem solved.
makrospecials.net/zamob/

Collapse
 
kinglavish0321 profile image
Dah_Mih_Rex

Good, well educative to read, Thank You
mstwotoes.com/mp3paw-download-free...

Collapse
 
erhankilic profile image
Erhan Kılıç

Awesome! Thanks.

Collapse
 
chathula profile image
Chathula Sampath

Great tutorial!! Got god understand about array stuff!

Collapse
 
ollieri3 profile image
Oliver R

This breakdown of array functions, was exactly what I was looking for. Thanks for taking the time to explain them!

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
andrew565 profile image
Andrew Steele

Thanks for your thoughts Rafael. This article is aimed at beginners, so I chose the easiest-to-read, more verbose way of expressing things.

Collapse
 
serener profile image
Seren

WapTrick is very great for games, app, videos and movies

Collapse
 
serener profile image
Seren

Wapdam is the new site which offer good movies and web series

Collapse
 
victoriaonu23 profile image
Victoriaonu23 • Edited

Nice to see all the code and the explanations. Really clarifying on this end