Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

254
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!