Sometimes, we want to get the item that appears the most times in an array with JavaScript.
In this article, we’ll look at how to get the item that appears the most times in an array with JavaScript.
How to get the item that appears the most times in an array with JavaScript?
To get the item that appears the most times in an array with JavaScript, we can use some object and array methods.
For instance, we write:
const store = ['1', '2', '2', '3', '4', '5', '5']
const counts = {}
for (const s of store) {
if (!counts[s]) {
counts[s] = 1
} else {
counts[s]++
}
}
const mostTimes = Math.max(...Object.values(counts))
const mostPopular = Object
.entries(counts)
.filter(([, count]) => count === mostTimes)
.map(([key]) => key)
console.log(mostPopular)
We loop through each store
entry and put the value as the keys of counts
and the count of each value as the value.
Then we get the highest count by getting the property values of counts
with Object.values
.
And then we get the max value with Math.max
and spreading the values from the array as arguments.
Next, we get the elements with the highest count with Object.entries
to return the key-value pairs as an array of key-value pair arrays.
Then we call filter
to get the items with count equals to mostTimes
.
Finally, we call map
to get the values with the highest count.
Therefore, mostPopular
is ['2', '5']
.
Conclusion
To get the item that appears the most times in an array with JavaScript, we can use some object and array methods.