DEV Community

Discussion on: Which Array Function When?

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