score:2

This doesnt have anything to do with ReactJS, which is a library for rendering and managing UI. In JS you can use a .reduce function to do that. I will produce and array with [{name: string, count: number}]:

const userArray = [{name: Riya, state: US}, {name: Chris, state: DE}]

const stateArray = userArray.reduce((newArray, currentElement) => {
  const stateExistsIndex = newArray.findIndex((state) => state.name === currentElement.state)
  if (stateExistsIndex !== -1) {
    const selectedState = newArray[stateExists] 
    newArray[stateExists] = { name: selectedState.name, count: selectedState.count++ }   
  } else {
    newArray.push({ name: currentElement.name, count: 1 })
  }

  return newArray
}, [])

This creates a new array. It loops through the old array and pushes an element to the new array if an state doesnt already exists. If it exists it increases its count by 1. You can of course also do it in a for-of loop which might be more easily understandable.


Related Query

More Query from same tag