Coder Perfect

Counting the number of times an array element appears / the frequency with which it appears


In Javascript, I’m attempting to count the elements within an initial array of number values. In an ideal world, the outcome would be two new arrays, one for each unique element and the other for the number of times each element appears. I am, however, open to recommendations concerning the output format.

For instance, suppose the starting array was:

5, 5, 5, 2, 2, 2, 2, 2, 9, 4

Two fresh arrays would be produced after that. The first would include the names of all of the distinct elements:

5, 2, 9, 4

The number of times that element appeared in the initial array would be in the second:

3, 5, 1, 1

Because the number 5 occurs three times in the initial array, the number 2 occurs five times and 9 and 4 both appear once.

I’ve looked everywhere for a solution, but nothing appears to work, and everything I’ve attempted has turned out to be absurdly complicated. Any assistance would be much appreciated!

Thanks 🙂

Asked by Jack W

Solution #1

You can save the results in an object:

As a result, your counts object can now give you the count for a certain number:

console.log(counts[5]); // logs '3'

If you want to get an array of members, just use the keys() functions

keys(counts); // returns ["5", "2", "9", "4"]

Answered by typeof

Solution #2

Answered by adamse

Solution #3

Answered by Šime Vidas

Solution #4

If using underscore or lodash, this is the simplest thing to do:


Such that:

_.countBy([5, 5, 5, 2, 2, 2, 2, 2, 9, 4])
=> Object {2: 5, 4: 1, 5: 3, 9: 1}

You may then use the _.keys() and _.values() functions on the result to get simply the unique integers and their occurrences, as others have pointed out. However, in my experience, dealing with the original object is considerably easier.

Answered by radicand

Solution #5

ES6 solution in a single line. There are a lot of replies that use an object as a map, but I don’t see anyone using a real map.

const map = arr.reduce((acc, e) => acc.set(e, (acc.get(e) || 0) + 1), new Map());

To acquire unique items, use map.keys().

To get the occurrences, use map.values().

To acquire the pairs [element, frequency], use map.entries().

Answered by corashina

Post is based on