Awais Umar
Awais Umar

Reputation: 2075

jQuery/Javascript - Sort Parent Divs Based on A number in Child Divs

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.

Upvotes: 0

Views: 1471

Answers (1)

Andrea Salicetti
Andrea Salicetti

Reputation: 2483

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

Upvotes: 7

Related Questions