Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
How to find top recurring items in an array in javascript

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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

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!

about 4 years ago · Juan Pablo Isaza Report

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!