Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

256
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda