一次排序多个数组 [英] Sorting multiple arrays at once

查看:117
本文介绍了一次排序多个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个数组:


  • 数组1是名字John,Jim,Jack,Jill

  • array 1 is "Name" John, Jim, Jack, Jill

数组2是年龄25,30,31,22

array 2 is "Age" 25, 30, 31, 22

数组3是性别 男性,男性,男性,女性

array 3 is "Gender" Male, Male, Male, Female

我将这些全部列在一个带有可排序标题的表中。现在排序工作正常,它按名称列进行排序。我怎样才能对年龄和性别数组进行排序以保持正确。我需要同时对所有3个进行排序。

I have these all listed in a table with a sortable header. Now the sort works fine, it sorts by the "Name" column for example. How can i also make it sort the "Age" and "Gender" arrays to keep them correct. I need to sort all 3 simultaneously.

_nameArray.sort(function(a, b){
    return ((a < b) ? -1 : ((a > b) ? 1 : 0));
})

希望它解释得很好。

没有结构不能改变,它的方式必须是3个数组,而不是一,只是按数组中的字段排序。

No the structure can not be changed, the way things are it has to be 3 arrays, not one and just sort by the field in the array.

推荐答案

即使从多个数组构造对象可能是理想的。您也可以使用间接在没有对象创建开销的情况下执行此操作。

Even though constructing Objects from the multiple arrays may be ideal. You can also do it without the object creation overhead using indirection.

/* An array of indexes */
var idx = [];
for (var i = 0; i < Name.length; i++) {
    idx.push(i);
}

/* A shorthand function */
var comparator = function(arr) {
    return function(a, b) {
        return ((arr[a] < arr[b]) ? -1 : ((arr[a] > arr[b]) ? 1 : 0));
    };
};

/* Sort by Age */
idx = idx.sort(comparator(Age));

/* Get the sorted order */
for (var i = 0; i < Name.length; i++) {
    console.log(Name[idx[i]], Age[idx[i]], Gender[idx[i]]);
}​

idx array包含其他数组元素的索引, idx [i] 。通过使用间接,您可以访问名称年龄性别;也就是说,名称[idx [i]]

The idx array contains indexes to the elements of the other arrays, idx[i]. By using indirection you can access the element in Name, Age and Gender; that is, Name[idx[i]].

如果性能有问题,那么构造对象可能是使用就地排序更快,如果你只做一次。否则,我会使用间接而不会触及真正的数组。

If performance is a problem then constructing the objects may be faster using in-place sorting, if you just do it once. Otherwise, I would use the indirection without never touching the real arrays.

那里你去。

注意比较器函数只是一个例子,你需要根据你的标准实际创建自己的比较器函数。

Note: The comparator function is just an example, you need to actually create your own comparator functions based on your criteria.

这篇关于一次排序多个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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