How to find top recurring items in an array in javascript

Viewed 71

So let's say I have an array of country name strings i.e

const array = ["usa", "spain", "canada", "usa", "usa", "spain"]

How would I go about looping through that array and generating a list that increments the most popular items in that array and lists only the top 3 for example?

For a more context, the actual use case is with hundreds of array items with dozens or even hundreds of different countries.

I know I can just loop through the array and create a new array and increment each time a particular string recurs again, but I was just curious if anybody has a cleaner and more universal approach.

Desired output:

usa: 3
spain: 2
canada: 1

Thank you for your time.

4 Answers

You can make use of Array.reduce:

const array = ["usa", "spain", "canada", "usa", "usa", "spain"]

const obj = array.reduce((a, b) => { return a[b] = array.filter(e => e == b).length, a }, {})

console.log(obj);

This ain't really pretty, but I think it's the most js-like snippet I can provide you

const array = ["usa", "spain", "canada", "usa", "usa", "spain"]

const result = array.reduce((acc, cur) => {acc[cur] = (acc[cur] ?? 0) + 1; return acc}, {})

console.log(result)

Surely this can be done in a better way though!

Simple yet most intuitive solution.

const arr = ["usa", "spain", "canada", "usa", "usa", "spain"];
let results = {};

for (let country of arr) {
  results[country] = (results[country] || 0) + 1;
}

console.log(results);

Get the occurrences of each items using reduce followed by getting top 3 objects by sorting its values and then using reduce to get the top 3 key-value pairs.

const data = ["usa", "spain", "canada", "usa", "usa", "spain"];

// Find the occurrences of each item
const countMap = data.reduce((acc, curr) => {
  acc[curr] = (acc[curr] || 0) + 1;
  return acc;
}, {});

// Sort the object by values and get the top 3
const sorted = Object.keys(countMap)
  .sort((a, b) => countMap[b] - countMap[a])
  .slice(0, 3);

// Get the desired key-count pair
const result = sorted.reduce(
  (acc, item) => ({
                    ...acc,
                    [item]: countMap[item]
                 })
,{});
console.log(result);

Related