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

65
Vistas
Sorting a array by its object value

I want to sort this array by its xp object:

[
  ["438449925949489153", {
    "xp": 2
  }],
  ["534152271443415140", {
    "xp": 3
  }],
  ["955210908794236938", {
    "xp": 1
  }]
]

So that it returns this array:

[
  ["955210908794236938", {
    "xp": 1
  }],
  ["438449925949489153", {
    "xp": 2
  }],
  ["534152271443415140", {
    "xp": 3
  }]
]

I've tried to do this with the sort-json npm module but it sorted the first value instead of xp

const sortJson = require('sort-json');
sortJson(array)
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can just use the native sort:

let data = [
  ["438449925949489153", {
    "xp": 2
  }],
  ["955210908794236938", {
    "xp": 3
  }],
  ["955210908794236938", {
    "xp": 1
  }]
];

const ascending = (a,b) => a[1].xp - b[1].xp;
const descending = (a,b) => b[1].xp - a[1].xp;

data.sort(ascending);

console.log(data)

data.sort(descending);

console.log(data)

Notice that sort mutates the original array: if you don't want to do that, you need do perform a shallow copy of the original array.

about 4 years ago · Juan Pablo Isaza Denunciar

0

sort descending:

arr.sort((a,b) =>{
    if (a[1].xp < b[1].xp) return 1
    else return -1
})

sort ascending:

arr.sort((a,b) =>{
    if (a[1].xp < b[1].xp) return -1
    else return 1
})
about 4 years ago · Juan Pablo Isaza Denunciar

0

I would suggest a bit more clean implementation:

function compare( a, b ) {
  if ( a[1] < b[1]){
    return -1;
  }
  if ( a[1] > b[1] ){
    return 1;
  }
  return 0;
}
    
arr.sort( compare );

Or one-liner:

arr.sort((a,b) => (a[1] > b[1]) ? 1 : ((b[1] > a[1]) ? -1 : 0))
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