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

209
Visualizações
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 Respostas
Responde à pergunta

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 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