Find the highest recurring duplicates in a JavaScript array

Let's assume that we are working with the following array:

javascript
let array = ['Erik', 'Andrea', 'Paula', 'Erik', 'Andrea'];

If we want to count the occurrences (frequency) of the array elements:

javascript
// Object to count occurrences
let counter = {};

// If name exists, we add 1 occurrence, otherwise we set counter to 1
array.forEach(name => counter[name] ? counter[name] ++ : counter[name] = 1);

console.log(counter);
// {Erik: 2, Andrea: 2, Paula: 1}

If we want to find the highest duplicate value(s):

javascript
// Getting max number of occurrences
let max = Math.max(...Object.values(counter));

// Getting array of highest duplicate values
let highest = Object.entries(counter).filter(([name, reps]) => reps === max);

console.log(highest);
// [['Erik', 2], ['Andrea', 2]]

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.