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.

1

1 Answer 1

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.

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

3 Comments

please add the code that loads the xml into xml variable. and where is $marker variable?
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++) { ..... }
@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.

Your Answer

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