DEV Community

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

Posted on • Updated on

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

Discussion (2)

lukeshiru profile image

You could use destructuring and nullish coalescing:

const occurrenceMap = array => array.reduce((output, current) => ({ ...output, [current]: (output[current] ?? 0) + 1 }), {});
Enter fullscreen mode Exit fullscreen mode


martinkr profile image
martin krause Author

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.