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

160
Visualizações
How to sort an array by a number inside w/ javascript

So I'm having trouble sorting an array. I'm trying to make it descend from the highest average to the lowest. This is the table ->

[
    {
        "average": "86.8",
        "user": "User1"
    },
    {
        "average": "93",
        "user": "User2"
    },
    {
        "average": "91.5",
        "user": "User3"
    }
]

This is how I set the array

let usr = []
if (users.docs.length > 0) {
    for (const user of users.docs) {
        let exportable = user.data()
        usr.push(exportable)
    }
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

try this.

https://stackblitz.com/edit/js-vb6yxa

const data = [
  {
    average: '86.8',
    user: 'User1',
  },
  {
    average: '93',
    user: 'User2',
  },
  {
    average: '91.5',
    user: 'User3',
  },
];

const sortedData = data.sort((a, b) => b.average - a.average);
console.log(sortedData);

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

The reason why this works per MDN "If compareFunction is not supplied, all non-undefined array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order.". When you provide a compare function to the sort() method, it instead sorts by number. a - b sorts in ascending order, while b - a does the opposite.

Here a link to a comment that explains this behavior more clearly: https://forum.freecodecamp.org/t/arr-sort-a-b-a-b-explanation/167677/3

about 4 years ago · Juan Pablo Isaza Relatório

0

use this.

const data = [
    {
        average : "86",
        user : 'user1',
    },
    {
        average : "93",
        user : 'user2',
    },
    {
        average : "91",
        user : 'user3',
    },
];
console.log(data.sort(function(a,b){return b.average - a.average}) );

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