开发者

sort array keys by value

开发者 https://www.devze.com 2023-02-17 09:01 出处:网络
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

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开发者_StackOverflow value of the new list for every insertion.

Anyone have a simpler method for this?


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.


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]
0

精彩评论

暂无评论...
验证码 换一张
取 消