Pete
Pete

Reputation: 23

sort array keys by value

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?

Upvotes: 2

Views: 7080

Answers (2)

Iulius Curt
Iulius Curt

Reputation: 5104

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]

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385108

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.

Upvotes: 4

Related Questions