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