Suppose I have a Javascript array, like so:
var test = ['b', 'c', 'd', 'a'];
I want to sort the array. Obviously, I can just do this to sort the array:
test.sort(); //Now test is ['a', 'b', 'c', 'd']
But what I really want is an array of indices that indicates the position of the sorted elements with respect to the original elements. I'm not quite sure how to phrase this, so maybe that is why I am having trouble figuring out how to do it.
If such a method was called sortIndices(), then what I would want is:
var indices = test.sortIndices();
//At this point, I want indices to be [3, 0, 1, 2].
'a' was at position 3, 'b' was at 0, 'c' was at 1 and 'd' was a 2 in the original array. Hence, [3, 0, 1, 2].
One solution would be to sort a copy of the array, and then cycle through the sorted array and find the position of each element in the original array. But, that feels clunky.
Is there an existing method that does what I want? If not, how would you go about writing a method that does this?
I would just fill an array with numbers 0..n-1, and sort that with a compare function.
Dave Aaron Smith is correct (I cannot comment), however I think it is interesting to use Array map() here.
You can accomplish this with a single line using es6 (generating a
0->N-1
index array and sorting it based on the input values).YMMV on how you feel about adding functions to the Array prototype and mutating arrays inline, but this allows sorting of an array of any objects that can be compared. It takes an optional function that can be used for sorting, much like
Array.prototype.sort
.An example,
Edit
You guys are right about
for .. in
. That will break if anybody munges the array prototype, which I observe annoyingly often. Here it is with that fixed, and wrapped up in a more usable function.