2

I'm using javascript, and I have an array containing multiple values, which may be non-unique. I'd like to take this array and generate a new array, or ordered list, of its keys in ascending order of value. For example, if I have [ 2, 2, 4, 5, 1, 6 ], I'd like to generate [ 5, 4, 0, 1, 2, 3 ].

I was thinking of iterating over the original list and inserting each value into the new list while checking for proper placement by comparing to the existing values of the new list every time an insertion is performed. This seems wasteful, though, as I'd have to (potentially) check every value of the new list for every insertion.

Anyone have a simpler method for this?

asked Mar 16, 2011 at 14:41
1
  • How does [5,4,0,1,2,3] follow from [2,2,4,5,1,6]? Commented Dec 13, 2016 at 2:51

2 Answers 2

4

I think you meant [ 4, 0, 1, 2, 3, 5 ].

function GetSortedKeys(values) {
 var array_with_keys = [];
 for (var i = 0; i < values.length; i++) {
 array_with_keys.push({ key: i, value: values[i] });
 }
 array_with_keys.sort(function(a, b) {
 if (a.value < b.value) { return -1; }
 if (a.value > b.value) { return 1; }
 return 0;
 });
 var keys = [];
 for (var i = 0; i < array_with_keys.length; i++) {
 keys.push(array_with_keys[i].key);
 }
 return keys;
}
var array = [2, 2, 4, 5, 1, 6];
alert(GetSortedKeys(array));

This is the simplest method I can come up with on Javascript, unfortunately.

answered Mar 16, 2011 at 15:12
Sign up to request clarification or add additional context in comments.

5 Comments

This works and I like it better than what I had worked out. Thanks
I've since learned how we should iterate over arrays. See my edit.
@Athari: Could that be because this is not a sorting algorithm, do you think?
ah, but the question has the 'sorting' tag, so you can forgive the mistake :)
@LordAro This is why one shall not make assumptions based upon a mere tag. :)
0

Using the nice Underscore.JS:

var get_sorted_keys = function(values) {
 var keys_idx = [], i;
 for (i = 0; i < values.length; i++) {
 keys_idx.push(i);
 }
 var keys = _.sortBy(keys_idx, function(idx){ return values[idx]; });
 return keys;
};
var array = [2, 2, 4, 5, 1, 6];
console.log("Sorted keys:", get_sorted_keys(array));

Output:

Sorted keys: [4, 0, 1, 2, 3, 5]
answered Apr 25, 2013 at 17:31

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.