'Sort array with string keys and integer values [closed]
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;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
