You can use Array#sort
for that:
myArray.sort(function(a, b) {
return a[1] - b[1];
});
...assuming that the [1]
entries in the sub-arrays are in fact numbers.
See live example below.
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.
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.
Live Example | Live Source:
// [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]);
}
Output:
0: 2 - 7.5
1: 3 - 8.99
2: 4 - 12.25
3: 5 - 13.72
4: 1 - 14.95