Skip to content

Counting the occurrences in an array

I have a simple array such as:

[
  "Selkatreeni",
  "Jalkatreeni",
  "Selkatreeni",
  "Selkatreeni",
  "Jalkatreeni",
  "Jalkatreeni",
  "Jalkatreeni",
  "Rintatreeni",
]

I want to display the element that has the highest occurrence, in this case “Jalkatreeni”. How should I go about doing it? Any neat tips are appreciated. 🙂

Thank you in advance!

Answer

Try the following. You can iterate through your array using .reduce(). In each iteration you take your whole array (arr) which is the fourth argument in the reduce() and .filter() that array for your accumulator (=the result of the reduce/our most frequent item in the array). If the length of the filtered arr is larger than the same filtered array but for the current iterated item (curr) we know our previous result (acc) occurs the most often. Otherwise we know it must be curr (the current iterated one). Finally we can return our new most frequent item so far and continue doing the same thing for the rest of the array.

Here’s a working example:

const data = [
  "Selkatreeni",
  "Jalkatreeni",
  "Selkatreeni",
  "Selkatreeni",
  "Jalkatreeni",
  "Jalkatreeni",
  "Jalkatreeni",
  "Rintatreeni",
];

const result = data.reduce((acc, curr, _, arr) =>
  arr.filter((item) => item === acc).length >
  arr.filter((item) => item === curr).length
    ? acc
    : curr
);

console.log(result);

In case you worry about the _ argument. This is just used as a placeholder for the unneeded third parameter in order to access the fourth one 😉