Home > Blockchain >  How to find the average of an array of numbers from an API and display it. The data is an array of o
How to find the average of an array of numbers from an API and display it. The data is an array of o

Time:10-28

So Im hitting an api and in the array of objects is an array of grades. Im mapping over the data but not sure how to go about getting the average grade and returning it in jsx. I tried the reduce method it didnt work and I just tried diving it by the length that didnt work either. I appreciate any help

data.map( ( element, index ) => {

    return (
        <div key={index} className="person-card" >
            <div><img src={element.pic} alt="pic" />
            </div>
            <div>
                <h2>
                    <strong>{element.firstName}    {element.lastName}</strong>
                </h2>
            </div>
            <div className="email">
                Email: {element.email}
            </div>
            <p> Company: {element.company}</p>
            <p>Skill: {element.skill}</p>
        </div>
    )
} )}

CodePudding user response:

There could be many ways to compute average, but this is one way using reduce.

const grades = [50, 40, 70];

const average = grades.reduce((acc, grades) => {
    return acc   grades
}, 0) / grades.length;

console.log(average);

Answer:

53.333333333333336

CodePudding user response:

Piggy Backing off Jagrut, reduce is the most viable option for finding the average of a sum of numbers. I believe your execution of his solution might be why reduce wasn't working for you. Here is an example using an array of sample data to find the average grade. You provided us with no example of how the data looks in the array you are mapping through so I had to guess.

const apiData = [
  { grades: [50, 60, 90], name: "billy" },
  { grades: [40, 80, 100], name: "jimmy" },
  { grades: [30, 50, 90], name: "Sam" }
];

export default function App() {
  const [data] = useState(apiData);

  return (
    <div className="App">
      {data.map((item, index) => {
        const average =
          item.grades.reduce((a, b) => {
            return a   b;
          }, 0) / item.grades.length;
        const roundedAverage = Math.floor(average);
        return (
          <>
            <div>Name: {item.name}</div>
            <div>average grade: {roundedAverage}</div>
          </>
        );
      })}
    </div>
  );
}

To see it in action here is a code sandbox as well: https://codesandbox.io/s/misty-paper-g2nfr?file=/src/App.js

  • Related