sajad torkamani

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
}

replit

Tagged: Snippets

Leave a comment

Your email address will not be published. Required fields are marked *