0

Lets say we have the following html div structure.

 <div class="article-container">

      <div class="article">
         <div class="article-child">views 9</div>
      </div>
      <div class="article">
         <div class="article-child">views 3</div>
      </div>
      <div class="article">
         <div class="article-child">views 5</div>
      </div>
      <div class="article">
         <div class="article-child">views 10</div>
      </div>
      <div class="article">
         <div class="article-child">views 1</div>
      </div>

 </div>

Using jQuery, how can I just clone/copy-paste the "article" divs in the ascending/descending order of the number coming in their children values. So I get result like this.

 <div class="article-container">

      <div class="article">
         <div class="article-child">views 10</div>
      </div>
      <div class="article">
         <div class="article-child">views 9</div>
      </div>
      <div class="article">
         <div class="article-child">views 5</div>
      </div>
      <div class="article">
         <div class="article-child">views 3</div>
      </div>
      <div class="article">
         <div class="article-child">views 1</div>
      </div>

 </div>

I was trying to prepare algorithm for it before I code. I know how to code in jQuery and the copy paste stuff but I am not sure how would I achieve this.

Awais Umar
  • 2,027
  • 3
  • 27
  • 46

1 Answers1

7

You can try this:

var cont = $(".article-container");
var arr = $.makeArray(cont.children(".article"));

arr.sort(function(a, b) {
  var textA = +$(a).find('.article-child').text();
  var textB = +$(b).find('.article-child').text();

  if (textA < textB) return 1;
  if (textA > textB) return -1;

  return 0;
});

cont.empty();

$.each(arr, function() {
    cont.append(this);
});

See demo here


If you must consider the text, you should use a regexp:

var cont = $(".article-container");
var arr = $.makeArray(cont.children(".article"));

arr.sort(function(a, b) {
  var textA = +$(a).find('.article-child').text().match(/views (\d+)/)[1];
  var textB = +$(b).find('.article-child').text().match(/views (\d+)/)[1];

  if (textA < textB) return 1;
  if (textA > textB) return -1;

  return 0;
});

cont.empty();

$.each(arr, function() {
    cont.append(this);
});

See demo here

Andrea Salicetti
  • 2,423
  • 24
  • 37
  • This is a good approach. I am giving it a try. Will share the response here in a while. Thank you. – Awais Umar Aug 19 '15 at 08:35
  • Please, read again, I've made a little fix to match exactly your sort order – Andrea Salicetti Aug 19 '15 at 08:38
  • This is exactly working for if I have numbers only on the child div. What if I have strings along with the numbers in the child elements. I guess we will have to use regex to get numbers out of it. Let me edit the question. And really very thankful to this help. – Awais Umar Aug 19 '15 at 08:52