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

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

    you can do this !

    
    detailItems.slice()
       .map((r, ix) => {
           r._ix = ix;
           return r;
       })
       .sort((a,b) => {
          ... /* you have a._ix or b._ix here !! */
       })
    
    

    .slice() clones your array to prevent side effects :))

    0 讨论(0)
  • 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});
    
    0 讨论(0)
提交回复
热议问题