Prabu
Prabu

Reputation: 2298

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;
});

Upvotes: 3

Views: 4015

Answers (1)

AnthonyWJones
AnthonyWJones

Reputation: 189437

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.

Upvotes: 4

Related Questions