DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,503 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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 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 (2)

Collapse
 
lukeshiru profile image
Luke Shiru

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

Cheers!

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

Cheers!

🌚 Friends don't let friends browse without dark mode.

Just kidding, it's a personal preference. But you can change your theme, font, etc. in your settings.

The more you know. 🌈