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

查看:74
本文介绍了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天全站免登陆