Riya Yadav
Riya Yadav

Reputation: 177

How can i get array of object from this data for state and count in reactjs

I am having data file in this array of objects form[{name,state},{name,state},{name,state},{name,state},{name,state}] I need the state data and number of people belonging to same state, for that i need an array of objects having state and it's count like [{state,count},{state, count},{state,count}] How can i get this reactjs?

Upvotes: 4

Views: 105

Answers (1)

Chrissi Grilus
Chrissi Grilus

Reputation: 1375

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.

Upvotes: 2

Related Questions