【问题标题】:Sort array and return an array of indicies that indicates the position of the sorted elements with respect to the original elements (new) [closed]排序数组并返回一个索引数组,指示排序元素相对于原​​始元素的位置(新)[关闭]
【发布时间】:2013-09-21 21:33:50
【问题描述】:

我有这个数组

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”上有两个元素具有相同的值时都会增加位置值。

【问题讨论】:

  • 到目前为止您尝试过什么?请发布您的代码并解释什么不起作用,如果可能的话,通过现场演示来重现问题。
  • 除了@Dave Aaron Smith 在链接帖子中提出的解决方案外,我什么都没尝试。从中我得到一个数组:[1,2,2,3]...

标签: javascript arrays sorting indexing


【解决方案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 ]

【讨论】:

猜你喜欢
  • 2011-04-13
  • 1970-01-01
  • 2017-11-02
  • 2019-04-27
  • 2013-01-04
  • 1970-01-01
  • 2021-06-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多