Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

208
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!