0

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];});
6
  • try a.sort(function(a,b){return a[1] > b[1];}); ? negatives value returns true, I think Commented Feb 15, 2011 at 15:50
  • 3
    What error are you seeing? That code works, at least for the main sort: jsbin.com/ulite3 Commented Feb 15, 2011 at 15:50
  • 2
    @BiAiB: No, the function that sort calls is expected to return <0 if a should be before b, >0 if a should be after b, or 0 if they're the same. Commented Feb 15, 2011 at 15:51
  • 1
    the code you've provided has the output you wanted Commented Feb 15, 2011 at 15:51
  • @T.J. Crowder: Regarding your comment to my (incorrect) answer: The code shown above to set up the array would not work as it is. One would still have to do a[i] = [] and a = []. Commented Feb 15, 2011 at 15:55

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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
*/

Comments

0

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);

1 Comment

His code works fine; yours gives the array backward. See jsbin.com/ulite3 (his version).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.