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

212
Vistas
Sort array with string keys and integer values

I'm trying to sort a Javascript array. All the values in the array are numeric. I'm trying to make use of the .sort function for this. But it doesn't seem to work when I have strings as keys in my array.

For example:

// Doesn't work
let numbers = [];
numbers['a'] = 5;
numbers['ld'] = 2;
numbers['la'] = 3;

numbers.sort((a, b) => {
    console.log('sort', a,b); // No output
    return 0;
});

But something simple like this does work.

// Works
let numbers2 = [100,10,50];
numbers2.sort((a, b) => {
    console.log('sort', a,b);
    return a-b;
});

console.log(numbers2);

Demo: https://jsfiddle.net/

What am I doing wrong? How can I sort the first array based on the values?

So basically what I'm trying to achieve is to get an array sorted like this based on their value (ascending or descending, doesn't matter for me):

numbers['a'] = 5;
numbers['la'] = 3;
numbers['ld'] = 2;
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You should not use strings as "keys"/"indices" in an array as they will not be accessed by the default array methods. Arrays use numeric indices to reference a value. You could use a object as key value storage. In objects you can use strings as keys to reference a value. You could then sort the object as follows.

let numbers = {};
numbers["a"] = 5;
numbers["ld"] = 2;
numbers["la"] = 3;

numbers = Object.fromEntries(Object.entries(numbers).sort((a, b) => {
  return a[1] - b[1]
}));
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