0

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!

4
  • 3
    That doesn't make any sense. Sorting is that act of changing elements' indexes so that the corresponding elements are in some order. If you don't change the index, you don't change the order. Sounds like what you want is an array of objects, or an array of arrays. Commented Sep 30, 2020 at 17:24
  • 2
    *Why* do you need this? Seems like an XY problem? Commented Sep 30, 2020 at 17:24
  • 1
    An array is by definition iterated from 0 to arr.length - 1. Even if you could reliably change the order of properties (indexes), with most iteration methods that becomes irrelevant. Use a different data structure that keeps order independent of keys, e.g. [[20, 10], ...]. Commented Sep 30, 2020 at 17:25
  • 2
    The index is not an actual value attached to the item - it is just a pointer. [0] will always point to the first item, [1] will always point to the second item, and so on. If you need to keep BOTH "index" and item, you have to put the data into some other object or add the value into the item itself. But, why is the "index" value so important that you need to keep it? Commented Sep 30, 2020 at 17:29

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.