I have an JavaScript arraylike this:
a[0][0] = "apple";
a[0][1] = 6.5;
a[1][0] = "orange";
a[1][1] = 4.3;
a[2][0] = "pear";
a[2][1] = 3.1;
I want to sort by the float number field in ascending order and assign the content in ascending order as well.
i.e.
a[0][0] = "pear";
a[1][1] = 3.1;
a[1][0] = "orange";
a[1][1] = 4.3;
a[2][0] = "apple";
a[2][1] 开发者_开发问答= 6.5;
I have tried sorted the content but the code seems does not allow float number.
Also, I do not know how to reassign the content in ascending order. Can anyone help me?
a.sort(function(a,b){return a[1] - b[1];});
Provided the parts of your code that you haven't quoted are correct, that should work
var index;
var a = []; // inferred
a[0] = []; // inferred
a[1] = []; // inferred
a[2] = []; // inferred
a[0][0] = "apple";
a[0][1] = 6.5;
a[1][0] = "orange";
a[1][2] = 4.3;
a[2][0] = "pear";
a[2][3] = 3.1;
a.sort(function(a,b){
return a[1] - b[1];
});
for (index = 0; index < a.length; ++index) {
display(a[index].join());
}
Live copy
Output:
pear,3.1 orange,4.3 apple,6.5
Off-topic: A more efficient, and perhaps clearer, way to initialize that array:
var a = [
["apple", 6.5],
["orange", 4.3],
["pear", 3.1]
];
Live copy
Did you create the array correctly? Your sort function is correct...
var a=[['apple',6.5],['orange',4.3],['pear',3.1]];
a.sort(function(a,b){return a[1]-b[1]});
/* returned value: (Array)
pear,3.1,orange,4.3,apple,6.5
*/
You just need to change the a, b order in the sort function
a.sort(function(a,b){return b[1] -a[1];});
try this in your firebug, , dragonfly or webkit console
var a = [["apple",6.5],["orange",4.3],["pear",3.1]];
a.sort(function(a,b){return b[1] -a[1];});
console.log(a);
精彩评论