28

After creating a multi-dim array like this, how do I sort it?

Assuming 'markers' is already defined:

var location = [];
for (var i = 0; i < markers.length; i++) {
  location[i] = {};
  location[i]["distance"] = "5";
  location[i]["name"] = "foo";
  location[i]["detail"] = "something";
}

For the above example, I need to sort it by 'distance'. I've seen other questions on sorting arrays and multi-dim arrays, but none seem to work for this.

3 Answers 3

46
location.sort(function(a,b) {

  // assuming distance is always a valid integer
  return parseInt(a.distance,10) - parseInt(b.distance,10);

});

javascript's array.sort method has an optional parameter, which is a function reference for a custom compare. the return values are >0 meaning b first, 0 meaning a and b are equal, and <0 meaning a first.

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

3 Comments

This worked, although "distance" was a decimal (like "964.543") so parseInt had to be removed, otherwise the sorting wasn't accurate past the decimal point.
@Deca parseFloat(a.distance) would be proper in that case.
Works like a frickin' charm! So simple, but perfect.
10

Have you tried this?

location.sort(function(a,b) {
    return a.distance - b.distance;
});

Comments

1

Both sort functions posted so far should work, but your main problem is going to be using location as a variable as it is already system defined.

1 Comment

+1 good point. But it isn't really an answer... :) You should've commented on one of them.

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.