Jeff
Jeff

Reputation: 2862

Javascript: sort multidimensional array

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.

Upvotes: 28

Views: 36299

Answers (3)

Gus
Gus

Reputation: 7349

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.

Upvotes: 1

user113716
user113716

Reputation: 322452

Have you tried this?

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

Upvotes: 10

lincolnk
lincolnk

Reputation: 11238

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.

Upvotes: 46

Related Questions