对数组进行排序并返回一个索引数组,这些索引指示已排序元素相对于原​​始元素的位置(新)

时间:2013-09-21 21:33:51

标签: javascript arrays sorting indexing

我有这个数组

test = [3, 2, 2, 1];

我希望能够获得这个数组

result = [3, 1, 2, 0]

这个想法与:Javascript: Sort array and return an array of indicies that indicates the position of the sorted elements with respect to the original elements

相同

但每次“test”上有两个元素具有相同的值时,递增位置值。

1 个答案:

答案 0 :(得分:1)

您可以传递比较函数进行排序:

var test = [3, 2, 2, 1];

var result = [];
for(var i = 0; i != test.length; ++i) result[i] = i;
result = result.sort(function(u,v) { return test[u] - test[v]; })
console.log(result) // [ 3, 1, 2, 0 ]