1

I am pushing list items into an array which have a data-sort value on them. When calling them back from the array I need to output them in their data-sort order where 1 would come first, 2 second, and so on. However if the data-sort is equal to 0, I need to do something completely different with the item.

JS

var arr = [];
$('ul li').each(function() {
  arr.push($(this));
});

$('ul.main').html('');
$.each(arr, function (i) {
  var item = arr[i];
  var content = $(item).html();
  var itemSort = $(item).data('sort'); //Need to sort by this value
  if(itemSort != '0') {
    $('ul.main').append('<li>' + content + '</li>')
  } else {
    $('.another-list').append('<li>' + content + '</li>'); // Sort order of 0's doesn't matter
  }
});

HTML

<ul class="main">
  <li data-sort="3">Item 1</li>
  <li data-sort="2">Item 2</li>
  <li data-sort="1">Item 3</li>
  <li data-sort="0">Item 4</li>
</ul>
<ul class="another-list"></ul>
5
  • Does your code produce errors? If so please edit your question adding the errors. Your question seems like it's about to describe the troubles you're having, but then it just hits a brick wall. Commented Feb 6, 2015 at 15:41
  • @JonnyHenly right now there is no code in there to actually control the order in which the data is output from the array, so no errors yet. I am not sure how to even use javascript/jQuery to sort by data within the array. Commented Feb 6, 2015 at 15:44
  • BTW, why do you push the element into "contactOptions" and then use "arr" in the "each" function ? Commented Feb 6, 2015 at 15:48
  • Is contactOption in the third line supposed to read arr? Commented Feb 6, 2015 at 15:50
  • yes, just changed that, sorry :) Commented Feb 6, 2015 at 15:51

1 Answer 1

3

The need to create an array from the selected elements is redundant as a jQuery object is an array of the selected elements.

Also, the need to take the html() of an li and then create that in an entirely new li is redundant as you can move elements from one list to another by just using append().

With that in mind you can massively simplify your code by using a combination of sort() and filter():

$('li').sort(function(a, b) {
    return $(a).data('sort') > $(b).data('sort');
}).appendTo('.main').filter(function() {
    return $(this).data('sort') == 0;
}).appendTo('.another-list');

Example fiddle

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

2 Comments

This is why we pay you the big money(I hope). Thank you for helping me think of this in a more simple manner!
I wish ;) Glad to help

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.