Javascript:对数组进行排序并返回一个指示数组,指示已排序元素相对于原​​始元素的位置 [英] Javascript: Sort array and return an array of indicies that indicates the position of the sorted elements with respect to the original elements

查看:96
本文介绍了Javascript:对数组进行排序并返回一个指示数组,指示已排序元素相对于原​​始元素的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个Javascript数组,如下所示:

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 this to sort the array:

test.sort(); //Now test is ['a', 'b', 'c', 'd']

但我真正想要的是一个索引数组,指示排序元素相对于原​​始元素的位置。我不太确定如何用这句话来表达,所以也许这就是为什么我无法弄清楚如何去做。

But what I really want is an array of indices that indicates the position of the sorted elements with respect to the original elements. I'm not quite sure how to phrase this, so maybe that is why I am having trouble figuring out how to do it.

如果这样的方法被称为sortIndices(),那么我想要的是:

If such a method was called sortIndices(), then what I would want is:

var indices = test.sortIndices();
//At this point, I want indices to be [3, 0, 1, 2].

'a'位于第3位,'b'位于0,'c'位于1并且'd'在原始数组中是2。因此,[3,0,1,2]。

'a' was at position 3, 'b' was at 0, 'c' was at 1 and 'd' was a 2 in the original array. Hence, [3, 0, 1, 2].

一种解决方案是对数组的副本进行排序,然后遍历排序的数组并找到位置原始数组中每个元素的数量。但是,这感觉很笨拙。

One solution would be to sort a copy of the array, and then cycle through the sorted array and find the position of each element in the original array. But, that feels clunky.

现有方法是否符合我的要求?如果没有,您将如何编写一个执行此操作的方法?

Is there an existing method that does what I want? If not, how would you go about writing a method that does this?

推荐答案

var test = ['b', 'c', 'd', 'a'];
var test_with_index = [];
for (var i in test) {
    test_with_index.push([test[i], i]);
}
test_with_index.sort(function(left, right) {
  return left[0] < right[0] ? -1 : 1;
});
var indexes = [];
test = [];
for (var j in test_with_index) {
    test.push(test_with_index[j][0]);
    indexes.push(test_with_index[j][1]);
}

修改

你们对于中的是正确的。如果有人打开阵列原型,那将会破坏,我经常烦恼地观察。这是固定的,并包含在一个更实用的函数中。

You guys are right about for .. in. That will break if anybody munges the array prototype, which I observe annoyingly often. Here it is with that fixed, and wrapped up in a more usable function.

function sortWithIndeces(toSort) {
  for (var i = 0; i < toSort.length; i++) {
    toSort[i] = [toSort[i], i];
  }
  toSort.sort(function(left, right) {
    return left[0] < right[0] ? -1 : 1;
  });
  toSort.sortIndices = [];
  for (var j = 0; j < toSort.length; j++) {
    toSort.sortIndices.push(toSort[j][1]);
    toSort[j] = toSort[j][0];
  }
  return toSort;
}

var test = ['b', 'c', 'd', 'a'];
sortWithIndeces(test);
alert(test.sortIndices.join(","));

这篇关于Javascript:对数组进行排序并返回一个指示数组,指示已排序元素相对于原​​始元素的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆