Tech Incent
Javascript

JS calculate the total 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

Explained RxJs switchMap operator with example

Sajal Mia

Javascript array methods example

Sajal Mia

Javascript string methods example

Sajal Mia

javascript memoization example

Sajal Mia

Higher Order Function in javascript

Sajal Mia