I'm looking for an elegant way of determining which element has the highest occurrence (mode) in a JavaScript array.
For example, in
['pear', 'apple', 'orange', 'apple']
the 'apple'
element is the most frequent one.
I'm looking for an elegant way of determining which element has the highest occurrence (mode) in a JavaScript array.
For example, in
['pear', 'apple', 'orange', 'apple']
the 'apple'
element is the most frequent one.
Time for another solution:
If brevity matters (it doesn't), then:
If non–existent members are to be avoided (e.g. sparse array), an additional hasOwnProperty test is required:
Other answers here will return undefined.
You can try this:
There have been some developments in javascript since 2009 - I thought I'd add another option. I'm less concerned with efficiency until it's actually a problem so my definition of "elegant" code (as stipulated by the OP) favours readability - which is of course subjective...
In this particular example, should two or more elements of the set have equal occurrences then the one that appears latest in the array will be returned. It's also worth pointing out that it will modify your original array - which can be prevented if you wish with an
Array.slice
call beforehand.Edit: updated the example with some ES6 fat arrows because 2015 happened and I think they look pretty... If you are concerned with backwards compatibility you can find this in the revision history.
As I'm using this function as a quiz for the interviewers, I post my solution:
Note: ct is the length of the array.