Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

136
Visualizações
How to get average from json?
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.
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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
about 4 years ago · Juan Pablo Isaza Relatório

0

This is more suitable

const average = arr => (arr.reduce((previousValue, currentValue) => parseInt(previousValue) + parseInt(currentValue)) / arr.length) || "Error occured at calculation";
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda