DEV Community

Cover image for 1 line of code: How to count all occurrences in an Array
Martin Krause
Martin Krause

Posted on • Edited on

17 4

1 line of code: How to count all occurrences in an Array

const occurrenceMap = arr => arr.reduce((acc, current) => (acc[current] = (acc[current] || 0) + 1, acc), {}); 
Enter fullscreen mode Exit fullscreen mode

Returns an object where the keys are the array entries and the values the number of their occurrences.


The repository & npm package

You can find the all the utility functions from this series at github.com/martinkr/onelinecode
The library is also published to npm as @onelinecode for your convenience.

The code and the npm package will be updated every time I publish a new article.


Follow me on Twitter: @martinkr and consider to buy me a coffee

Photo by zoo_monkey on Unsplash


Top comments (1)

Collapse
 
martinkr profile image
Martin Krause

Thank you for sharing! Yes, there are multiple other ways to achieve this task in javascript. As so often in programming, at one point you have to choose ;)

I checked the benchmarks and for me the alternative you provided is much slower (11,688 ops/sec vs. 7.81 ops/sec on jsbench). But of course there can be different performance results depending on the engine and environment as well as other factors for the decision which way to go.

Cheers!

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Dive into this informative piece, backed by our vibrant DEV Community

Whether you’re a novice or a pro, your perspective enriches our collective insight.

A simple “thank you” can lift someone’s spirits—share your gratitude in the comments!

On DEV, the power of shared knowledge paves a smoother path and tightens our community ties. Found value here? A quick thanks to the author makes a big impact.

Okay