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

82
Visualizações
React.js sort inside a map function

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();
about 4 years ago · Juan Pablo Isaza
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