4

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?

1
  • can you share what you did so far? code snippet ? please follow stackoverflow question guidelines How to Ask? - stackoverflow.com/help/how-to-ask Commented Apr 18, 2021 at 14:46

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I am getting this error using the above code "TypeError: newArray.findIndex is not a function"
sorry, its "indexOf" not findIndex and you have to check if its not -1 because thats the value it return when its not in the array
The currentElement is always undefined why is that?
The error is still occuring (TypeError): newArray.indexOf is not a function
Its the other way around, first parameter is the accumulator the second is the current value. Please check out the api for further info: developer.mozilla.org/de/docs/Web/JavaScript/Reference/… or just use a for-of loop: ``` let newArray = [] oldArray.forEach((element) => { if (newArray.findIndex(newElement => newElement.name === element.state) === -1) { // Push element to array } else { increment count on new array element by 1 } }) ```
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.