Count occurrences of items in array
15 March 2022 (Updated 21 July 2024)
You want a function that takes an array of scalar values and returns a hash/object where the key is the item and the value is the number of times that item occurs in the array.
getItemsCount(['a', 'b', 'b', 'a', 'c']))
// { a: 2, b: 2, c: 1 }
Here’s how:
function getItemsCount(arr) {
const itemsCount = {}
arr.forEach(item => {
itemsCount[item] = itemsCount.hasOwnProperty(item) ? itemsCount[item] + 1 : 1
})
return itemsCount
}
Tagged:
Snippets
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment