1

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.

8
  • @hindmost it's not relevant to se html markup for this. But ok. Commented Oct 18, 2016 at 8:26
  • Handlebars templates you using are quite relevant to your question. Commented Oct 18, 2016 at 8:28
  • you mean something like this: jsfiddle.net/znttxbwm ? Commented Oct 18, 2016 at 8:30
  • store the html element in the 'locations' object, then you can get refferance t o it Commented Oct 18, 2016 at 8:31
  • @AdiDarachi I do got a Id in the id that has a reference to the actual html element, but question is how do I do that? Commented Oct 18, 2016 at 8:35

1 Answer 1

1

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/

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

4 Comments

That is actually more like what I'm looking for. But there is no way to just sort? I'm thinking if this could be a performance issue.
how is this different from my answer?, it uses the same append function
@Dejan.S, The answer is no, there is no way to move html elements in the DOM rather then append/detach (adding/removing element from the DOM)
@madalinivascu, The difference is that you did it on execution-time and my function can be used after execution-time.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.