Reputation: 93
I am receiving a json object from my API and I am pushing it into my state. That object has a field called "grades". That grades is an array of objects that have a field called "mark".
I would like to take the "mark" from all the objects and push it into a new array / state in order to calculate the average "mark".
Here's my code that includes comments on what I would like to do:
const [trainee, setTrainee] = useState ({})
// state declaration for the trainee.grades.mark array
const [mark, setMark] = useState ([])
useEffect(() => {
fetch(`/api/trainees/${match.params.id}`)
.then(response => response.json())
.then(json => setTrainee(json))
// something here that pushes all trainee.grades.mark into mark through setMark
}, [])
// function that takes the state Mark array and calculates the average of it
function arrayAverage(arr){
//Find the sum
var sum = 0;
for(var i in arr) {
sum += arr[i];
}
//Get the length of the array
var numbersCnt = arr.length;
//Return the average / mean.
return (sum / numbersCnt);
}
// end result by calling the average calculator function and passing mark as an array in it
<Typography className={classes.title} color="textSecondary" gutterBottom>
AVERAGE GRADE
</Typography>
<Typography variant="body2" component="p">
{arrayAverage(mark)}
</Typography>
<Divider />
Here's the trainee object
_id: String
fullName: String
age: Number
author: {}
department: String
endDate: Date
startDate: Date
status: String
grades: [{ ._id: String
title: String
text: String
mark: Number
}]
Upvotes: 0
Views: 54
Reputation: 447
You could make marks array like this
useEffect(() => {
fetch(`/api/trainees/${match.params.id}`)
.then(response => response.json())
.then(json => {
setTrainee(json);
setMark(json.grades.map(grade => grade.mark));
})
}, [])
and to calculate average
function arrayAverage(arr){
//Find the sum
const sum = arr.reduce((accumulator, mark) => (accumulator + mark));
return sum / arr.length;
}
Upvotes: 2
Reputation: 181
There is no other way but to traverse through the entire array of grades. You can either use Array.map or a for loop to traverse the grades array. if the parsed object is like
let response = {
grades: [
{
mark: value
...
},
...
]
}
You can use
let marks = response.grades.map(grade => {
return grade.mark;
})
Now marks will contain a list of mark values. You can call setMarks(marks)
to update the state.
Upvotes: 0