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

68
Vistas
Sorting nested array not returning sorted results

I have the following code, which seems to be doing the correct thing, but when I log the array object it never changes:

let data = [
    {'country': 'AB', 'state': 'DE'},
    {'country': 'US', 'state': 'CA'},
    {'country': 'AB', 'state': 'DE'},
    {'country': 'US', 'state': 'MI'},
    {'country': 'RU', 'state': null}
];
function sortFunc(a, b) {
    let val = a['country'] < b['country'];
    console.log(a['country'], b['country'], val);
    return +val;
}
data.sort(sortFunc);
console.log(data);

What is the issue with the above code?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The sort function needs to go both ways and return 0 if equal or -1 or 1 -- the above function just returns 1 or 0. Here would be a proper version:

let data = [
    {'country': 'AB', 'state': 'DE'},
    {'country': 'US', 'state': 'CA'},
    {'country': 'AB', 'state': 'DE'},
    {'country': 'US', 'state': 'MI'},
    {'country': 'RU', 'state': null}
];
function sortFunc(_a, _b) {
    let [a,b] = [_a['country'], _b['country']];
    if (a===b)      return 0;
    else if (a>b)   return 1;
    else            return -1;
}
data.sort(sortFunc);
console.log(data);

about 4 years ago · Juan Pablo Isaza Denunciar

0

I don't know whether you want to sort it in ascending or descending, so just figure it out yourself from ternary operator. Rest I guess its working as you expect.

let data = [
    {'country': 'AB', 'state': 'DE'},
    {'country': 'US', 'state': 'CA'},
    {'country': 'AB', 'state': 'DE'},
    {'country': 'US', 'state': 'MI'},
    {'country': 'RU', 'state': null}
];
function sortFunc(a, b) {
    return a['country'] < b['country']?1:-1;
}
data = data.sort(sortFunc);
console.log(data);

enter image description here

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