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

204
Visualizações
Sort Array by attribute

I right now just get the first 3 Object of an Array and map over them:

<ul className="ItemSearchList"> 
  { 
    champions.slice(0,3).map(function(champ){
      return (
        <li key={champ.id} >
          <div className="media">
            <div className="media-left">
              <a href="#">
                <img className="media-object" src={"http://ddragon.leagueoflegends.com/cdn/5.2.1/img/champion/" + champ.key  + ".png"} />
              </a>
            </div>
            <div className="media-body" >
              <h4 className="media-heading">{champ.name}</h4>
              <div>
                something
              </div>
            </div>
          </div>
        </li>
      )
    }) 
  }
</ul>

Each champ has a level attribute (champ.level).

How can I sort my output to champ.level descending and slice the first 3?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Use Array.prototype.sort() with a custom compare function to do the descending sort first:

champions.sort(function(a, b) { return b.level - a.level }).slice(...

Even nicer with ES6:

champions.sort((a, b) => b.level - a.level).slice(...
over 4 years ago · Santiago Trujillo Relatório

0

Write your own comparison function:

function compare(a,b) {
  if (a.level < b.level)
     return -1;
  if (a.level > b.level)
    return 1;
  return 0;
}

To use it:

champions.sort(compare).slice(0,3).map(function(champ) {
over 4 years ago · Santiago Trujillo Relatório

0

The pure JS solutions are nice. But if your project is set up via npm, you can also use Lodash or Underscore. In many cases those are already sub-dependencies so no extra weight is incurred.

Combining ES6 and _.orderBy provided by lodash

_.orderBy(champions, [c => c.level], ['desc']).slice(0,3)

This is a powerful little utility. You can provide multiple tie-breaking sort keys to orderBy, and specify an order for each individually.

over 4 years ago · Santiago Trujillo 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