Reputation: 303
I have a array like this:
arr[1] = 100
arr[10] = 20
arr[20] = 10
When I iterate the array, I got:
arr[1]:100 arr[10]:20 arr[20]:10
Currently, the array is sorted by the index. How can I sort it by the value but KEEP the original index.
What I want is:
arr[20]:10 arr[10]:20 arr[1]:100
I checked other posts but didn't find a solution to this specific issue. I am not sure javascript supports this. Can I get some help?
Thanks!
Upvotes: 0
Views: 1239
Reputation: 351158
When we speak of a sorted array in JavaScript, we mean that an iteration over the array by increasing index produces the values in sorted order.
Your requirements would actually require an array with pairs of ("index", value).
Here is how that works:
let arr = [];
arr[1] = 100;
arr[10] = 20;
arr[20] = 10;
let result = Object.entries(arr).sort((a, b) => a[1]-b[1])
.map(([k, v]) => [+k, v]); // optional conversion
console.log(result);
Upvotes: 1