Tech Incent
JavaScript Snippets

JS calculate the number of elements in an array

// Calculate the number of elements in an array


const arr = [1, 5, 5, 3, 1, 5]
const result = arr.reduce((prevState, num) => {
  prevState[num] = prevState[num] ? prevState[num] + 1 : 1
  return prevState
}, {})

console.log('Result', result)

// Result
{
  1: 2,
  3: 1,
  5: 3
}

Related posts

Pure function in javascript

Sajal Mia