Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

161
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda