Dejan.S
Dejan.S

Reputation: 19138

Sort html from a sort order populated in an array

I'm trying to sort a html list by a distance, I do not want to put distance property in my markup. What I do is that I render the store list html, in js I create a array where I keep the store and distance.

locations = [];
locations.push({
    'store': stores[i],
    'cordinate': Math.random()
});

I sort that with this

locations.sort(dynamicSort('cordinate'));

function dynamicSort(property) {
  var sortOrder = 1;

  return function(a, b) {
    var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
    return result * sortOrder;
  }
}

Here is where I get stuck, how can I sort my html using this array? The key here is that I don't want to clutter my html with setting the cordinate there.

My fiddle is right here


EDIT
The question was about sorting the output html with the sort order populated in a array. There for I removed the html and other js that I only used because of being lazy to populate markup.

Upvotes: 1

Views: 163

Answers (1)

Adi Darachi
Adi Darachi

Reputation: 2175

Basically all you need to do, is call append on the html elements in the sort order.

This will append the element in the end of the html elements.

var sortHTML = function(locations) {
  $.each(locations, function(i, location) {
    var targetElement = $('#' + location.store.id);
    targetElement.parent().append(targetElement)
  });
};
sortHTML(locations);

fiddle here: https://jsfiddle.net/wbcj026x/1/

Upvotes: 1

Related Questions