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

255
Visualizações
How to sort sum up all values from object arrays inside react props

I would like to sort three top rated posts. The current function of displaying three post titles and their rating, but I can not sort them by best rating. Please help.

   {posts.slice(0, 3).map((p)=> (
                    <p className='bestTitle'>{p.title} {p.ratings && 
                         ((p.ratings.reduce(function(prev, current) 
                            {return prev + current.rating}, 0)/(20 * p.ratings.length)).toFixed(2)) }</p>
                ))}

The posts will look like this:

{
    posts: 
        {
            title: "abc",
            ratings:
                   username: "abc",
                   rating: 60
        }
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Assuming posts is an array, you can use javascript array sort.

But first, to make things easier to work with, we can preprocess the posts separately by adding/precalculating an averageRating field on each post.

After that, we can sort it and then you can use it where needed.

const posts = [{
    title: "a",
    ratings: [{
      username: "dave",
      rating: 10
    }]
  },
  {
    title: "b",
    ratings: [{
        username: "cam",
        rating: 5
      },
      {
        username: "lil",
        rating: 50
      }
    ]
  },
  {
    title: "c",
    ratings: [{
      username: "az",
      rating: 70
    }]
  }
];

// Process each post to store its average rating on the object
// This makes it easier for sorting.
averageRatingPosts = posts.map((post) => ({
  ...post,
  averageRating: post.ratings.reduce((prev, current) => prev + current.rating, 0) / (20 * post.ratings.length)
}));

// Sort by descending order/best average ratings on a scale of 1-5
averageRatingPosts.sort((postA, postB) => postB.averageRating - postA.averageRating);

// Posts are now sorted by descending order of their average ratings.
console.log(averageRatingPosts);

about 4 years ago · Juan Pablo Isaza Relatório

0

I don't recommend to do the sorting in the render function.

(Because you have to compute the overall rate for each post.)

Instead, you can first calculate the ratings and sort them. then show them on the render.

const [topPosts, setTopPosts] = useState([]);
useEffect(() => {
  // copy posts
  let posts_ = JSON.parse(JSON.stringify(posts));
  posts_.forEach(post => {
    post.rate = post.ratings &&
      parseFloat((post.ratings.reduce( (prev, current) => prev + current.rating, 0)
      / (20 * post.ratings.length)).toFixed(2))
  })
  posts_.sort((a, b) => b.rate - a.rate)
  posts_ = posts_.slice(0, 3);
  setTopPosts(posts_);
}, [posts])
return <div>
   {topPosts.map((p)=> (
     <p className='bestTitle'>{p.title} {p.rate || ''}</p>
   ))}
</div>
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