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

查看:12
本文介绍了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]);
}

编辑

你们是对的for .. in.如果有人修改数组原型,那将会中断,我经常恼人地观察到它.这是固定的,并包含在一个更有用的功能中.

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天全站免登陆