I am trying to sort a list of albums inside a map function. Basically this is my code for each list element.
{
album
&& album.map
&& album.map((d) => (
<Link className='link' to={{ pathname: '/itemPage/' + d.id, album: d }}>
{d.isSingle ? (
<ul className={'listNumber'}>
{' '}
<span className={'info'}>
{i++}. {d.artist} - {d.title} <b className={'rating'}>{getRating(d)}</b>
</span>{' '}
</ul>
) : (
''
)}
</Link>
));
}
getRating function to get sum of rating within reviews and get the average:
const getRating = (d) => {
if (d.reviews){
let newRating = ((d.reviews.reduce((a,b) => a + b.rating, 0))/d.reviews.length)
if(d.reviews.length === 0){
let newRating = 0;
return newRating
}
return newRating.toFixed(0)
}
}
An element of the album looks like this
name: "xxx"
id: "61a947a868f7d778e3ee73f8"
isSingle: true
reviews: Array(3)
0: {rating: 1, comment: 'Hallo', name: 'xxx', user: '61a60a98d321417a2b3c71b7', _id: '61ad1645fb30be6a012fe148'}
1: {rating: 8, comment: 'Hallo', name: 'xxx', user: '61a60a98d321417a2b3c71b7', _id: '61add5b8cf3cadd3de1a5dc5'}
2: {rating: 10, comment: 'xxxx', user: '61a60a98d321417a2b3c71b7', _id: '61addcb388adeac745f4cd5e'}
length: 3
[[Prototype]]: Array(0)
title: "
I am trying to sort the list by the average rating (reviews.rating sum / reviews.length)
Is there a way to sort it inside the map function above?
my current result is that it sorts by the amount of reviews, but that is not what I need, with this approach:
.map((objs, key) => ({
title: key,
artist: _.sumBy(objs, 'artist'),
id: _.sumBy(objs, 'id'),
isSingle: _.sumBy(objs, 'isSingle'),
reviews: _.sumBy(objs, 'reviews'),
}))
.orderBy(['reviews'], 'desc')
.slice(0, 20)
.value();