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

后端 未结 8 809
囚心锁ツ
囚心锁ツ 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:39

    Dave Aaron Smith is correct, however I think it is interesting to use Array map() here.

    var test = ['b', 'c', 'd', 'a'];
    // make list with indices and values
    indexedTest = test.map(function(e,i){return {ind: i, val: e}});
    // sort index/value couples, based on values
    indexedTest.sort(function(x, y){return x.val > y.val ? 1 : x.val == y.val ? 0 : -1});
    // make list keeping only indices
    indices = indexedTest.map(function(e){return e.ind});
    

提交回复
热议问题