import axios from 'axios';
import React, {useState, useEffect} from 'react';
function App() {
const [students, setStudents] = useState([]);
**const avg = arr => arr.reduce((a,b) => a + b, 0) / arr.length**
useEffect(() => {
axios
.get("URL")
.then((data) => setStudents(data.data.students));
}, []);
return (
<>
{students.map((student) => (
<div key={student.id}>
<p><h3> {student.firstName} {student.lastName}</h3></p>
<p>{student.email}</p>
<p>{student.company}</p>
<p>{student.skill}</p>
<p>{avg(student.grades)}</p>
</div>
))}
</>
);
}
export default App;
Hello I put a function to get the average value from the json, but it doesn't work. I don't know if the function is wrong or the location of the function is wrong. Can you please help me?
const avg = arr => arr.reduce((a,b) => a + b, 0) / arr.length
Above is the json file format.
Based on your json data, you'll need to convert the grades to numbers before they can be averaged, which can be done with map before reduce
const avg = arr => arr.map(grade => parseInt(grade)).reduce((a,b) => a + b, 0) / arr.length
This is more suitable
const average = arr => (arr.reduce((previousValue, currentValue) => parseInt(previousValue) + parseInt(currentValue)) / arr.length) || "Error occured at calculation";