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

后端 未结 8 832
囚心锁ツ
囚心锁ツ 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 accomplish this with a single line using es6 (generating a 0->N-1 index array and sorting it based on the input values).

    var test = ['b', 'c', 'd', 'a']
    
    var result = Array.from(Array(test.length).keys())
                      .sort((a, b) => test[a] < test[b] ? -1 : (test[b] < test[a]) | 0)
    

提交回复
热议问题