1

This is my sample xml

<markers>
    <marker location_id="1" title="test 1" distance="0.0832"/>
    <marker location_id="2" title="test 2" distance="3.1852"/>
    <marker location_id="3" title="test 3" distance="4.3761"/>
    <marker location_id="4" title="test 4" distance="3.3761"/>
</markers>
var entries = xml.documentElement.getElementsByTagName('marker');

How can I sort this entries by distance, ascending order ? I want to do it using Javascript.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339

1 Answers1

2

You can use the sort method:

var $markers = $('.marker', xml);
$markers.find('marker').sort(function(a, b) {
     return parseFloat($(a).attr('distance')) > parseFloat($(b).attr('distance'));
}).appendTo($markers);

This code assumes that the XML you have is stored in the xml variable.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • please add the code that loads the xml into `xml` variable. and where is `$marker` variable? – machineaddict May 26 '15 at 07:13
  • var entries = xml.documentElement.getElementsByTagName('marker'); after this, how can i use this ? var $markers = $('.marker', xml); $markers.find('marker').sort(function(a, b) { return parseFloat($(a).attr('distance')) > parseFloat($(b).attr('distance')); }).appendTo($marker); at the end, i am using loop to get the data. for(i = 0; i < entries.length; i++) { ..... } –  May 26 '15 at 07:15
  • @machineaddict `xml` is a variable in the OPs original code example, so I would assume he already has that. `$marker` was a typo which I have now corrected. – Rory McCrossan May 26 '15 at 07:15