以相同的方式对两个数组排序 [英] Sort two arrays the same way
问题描述
例如,如果我有这些数组:
For example, if I have these arrays:
var name = ["Bob","Tom","Larry"];
var age = ["10", "20", "30"];
我使用 name.sort()
name数组的顺序变为:
And I use name.sort()
the order of the "name" array becomes:
var name = ["Bob","Larry","Tom"];
但是,如何对name数组进行排序并使age数组保持不变订购?像这样:
But, how can I sort the "name" array and have the "age" array keep the same order? Like this:
var name = ["Bob","Larry","Tom"];
var age = ["10", "30", "20"];
推荐答案
您可以对现有数组进行排序,或重新组织数据。
You can sort the existing arrays, or reorganize the data.
方法1:
要使用现有数组,您可以对它们进行组合,排序和分离:
(假设等长数组)
var names = ["Bob","Tom","Larry"];
var ages = ["10", "20", "30"];
//1) combine the arrays:
var list = [];
for (var j = 0; j < names.length; j++)
list.push({'name': names[j], 'age': ages[j]});
//2) sort:
list.sort(function(a, b) {
return ((a.name < b.name) ? -1 : ((a.name == b.name) ? 0 : 1));
//Sort could be modified to, for example, sort on the age
// if the name is the same.
});
//3) separate them back out:
for (var k = 0; k < list.length; k++) {
names[k] = list[k].name;
ages[k] = list[k].age;
}
这样做的好处是不依赖于字符串解析技术,可以使用在任何数量的需要一起排序的数组上。
This has the advantage of not relying on string parsing techniques, and could be used on any number of arrays that need to be sorted together.
方法2:或者您可以稍微重新组织数据,然后排序对象集合:
Method 2: Or you can reorganize the data a bit, and just sort a collection of objects:
var list = [
{name: "Bob", age: 10},
{name: "Tom", age: 20},
{name: "Larry", age: 30}
];
list.sort(function(a, b) {
return ((a.name < b.name) ? -1 : ((a.name == b.name) ? 0 : 1));
});
for (var i = 0; i<list.length; i++) {
alert(list[i].name + ", " + list[i].age);
}
对于比较,-1表示较低的索引,0意味着相等,1意味着更高的指数。值得注意的是 sort()
实际上更改了基础数组。
For the comparisons,-1 means lower index, 0 means equal, and 1 means higher index. And it is worth noting that sort()
actually changes the underlying array.
这篇关于以相同的方式对两个数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!