[removed] Sort array and return an array of indicies that indicates the position of the sorted elements with respect to the original elements

后端 未结 8 806
囚心锁ツ
囚心锁ツ 2020-12-05 01:51

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 th

8条回答
  •  既然无缘
    2020-12-05 02:29

    Array.prototype.sortIndices = function (func) {
        var i = j = this.length,
            that = this;
    
        while (i--) {
            this[i] = { k: i, v: this[i] };
        }
    
        this.sort(function (a, b) {
            return func ? func.call(that, a.v, b.v) : 
                          a.v < b.v ? -1 : a.v > b.v ? 1 : 0;
        });
    
        while (j--) {
            this[j] = this[j].k;
        }
    }
    

    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,

    var test = [{b:2},{b:3},{b:4},{b:1}];
    
    test.sortIndices(function(a,b) { return a.b - b.b; });
    
    console.log(test); // returns [3,0,1,2]
    

提交回复
热议问题