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;
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]
}));