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?
-
can you share what you did so far? code snippet ? please follow stackoverflow question guidelines How to Ask? - stackoverflow.com/help/how-to-askLakshman Kambam– Lakshman Kambam2021-04-18 14:46:59 +00:00Commented Apr 18, 2021 at 14:46
Add a comment
|
1 Answer
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.
7 Comments
Riya Yadav
I am getting this error using the above code "TypeError: newArray.findIndex is not a function"
Chrissi Grilus
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
Riya Yadav
The currentElement is always undefined why is that?
Riya Yadav
The error is still occuring (TypeError): newArray.indexOf is not a function
Chrissi Grilus
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 } }) ```
|