Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting xml in javascript/jquery

I was trying to sort some xml with jquery, but this code doesn't affect the actual xml or not returning a sorted result.

Anything wrong with this code?

$(xml).find('Tag').get().sort(function(a, b) {
    return $(a).find('Name').text() < $(b).find('Name').text() ? -1 : 1;
});
like image 308
Prabu Avatar asked Aug 02 '26 03:08

Prabu


1 Answers

The get function creates and returns an array, your code then sorts this array, then what? The array isn't referenced anywhere so it just gets dropped.

I suspect you are expecting the source xml document to be mutated to represent this sort. Are you sure you want to mutate the xml or would access to the sorted array suffice?

var sortedSet = $(xml).find('Tag').get().sort(function(a, b) {
  var valA = $(a).find('Name').text();
  var valB = $(b).find('Name').text();
  return valA < valB ? -1 : valA == valB ? 0 : 1;
});

Mutating the xml is a little trickier especially if "Tag" is found deeper than as direct child of xml.

like image 50
AnthonyWJones Avatar answered Aug 04 '26 15:08

AnthonyWJones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!