如何通过一个字段进行排序jQuery的多维数组? [英] How to sort a multidimensional array in jquery by one field?
问题描述
我有这个数组中jQuery的:
I have this array in jquery:
var myArray = new Array();
myArray[1] = new Array();
myArray[2] = new Array();
myArray[3] = new Array();
myArray[4] = new Array();
myArray[5] = new Array();
元素 myArray的[X] [1]
(X可以是1至5)包含一个数值(价格)和元素 myArray的[X] [2]
另一个数字值(标识符)。我需要的价值下令阵列 myArray的[X] [1]
(价格),而不每个价格从他的标识符分离(他的 [ X] [2]
)。
The element myArray[x][1]
(x can be 1 to 5) contains a numeric value (a price) and the element myArray[x][2]
another numeric value (an identifier). I need to order the array by the value of myArray[x][1]
(the price) without separating every price from his identifier (his [x][2]
).
我如何?
推荐答案
您可以使用阵列#排序
为:
myArray.sort(function(a, b) {
return a[1] - b[1];
});
...假设 [1]
在子阵列条目是实际上的数字。
...assuming that the [1]
entries in the sub-arrays are in fact numbers.
请参见下面活生生的例子。
See live example below.
附注1:请注意,数组下标 0
开始,所以你的数组作为援引了未定义
(而不是在第一位置的子阵列)。你会想解决这个问题,通过执行下面做上述,可能之前。
Side note #1: Note that array indexes start at 0
, so your array as quoted has undefined
(rather than a sub-array) in the first position. You'll want to fix that before doing the above, possibly by doing the below.
边注2:在JavaScript中,几乎从来没有任何理由写新的Array()
。相反,只使用字面数组: []
。你报价code,例如,可以是:
Side note #2: In JavaScript, there is almost never any reason to write new Array()
. Instead, just use an array literal: []
. Your quoted code, for instance, could be:
var myArray = [
[],
[],
[],
[],
[]
];
...假设你解决上述确定的错误。
...assuming you fix the error identified above.
// [0] is the id, [1] is the price
var myArray = [
[1, 14.95],
[2, 7.50],
[3, 8.99],
[4, 12.25],
[5, 13.72]
];
myArray.sort(function(a, b) {
return a[1] - b[1];
});
var index, entry;
for (index = 0; index < myArray.length; ++index) {
entry = myArray[index];
console.log(index + ": " + entry[0] + " - " + entry[1]);
}
输出:
0: 2 - 7.5
1: 3 - 8.99
2: 4 - 12.25
3: 5 - 13.72
4: 1 - 14.95
这篇关于如何通过一个字段进行排序jQuery的多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!