Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order (sort) a <li> list with numeric content?

I have a list as below that is created dynamically:

<ul>
  <li>20</li>
  <li>10</li>
  <li>5</li>
  <li>3</li>
  <li>32</li>
  <li>25</li>
  <li>6</li>
  <li>12</li>
  <li>8</li>
</ul>

Is it possible order this list using jQuery? I need it ordered from lower to bigger, like this:

<ul>
  <li>3</li>
  <li>5</li>
  <li>6</li>
  <li>8</li>
  <li>10</li>
  <li>12</li>
  <li>20</li>
  <li>25</li>
  <li>32</li>
</ul>
like image 336
Marcio Mazzucato Avatar asked Apr 18 '12 18:04

Marcio Mazzucato


People also ask

How do I order a list in R?

Sorting or Ordering a list in R can be done by using lapply() function or using the order() function after converting to a vector using unlist().

How do you sort values in HTML?

Adding the "sortable" class to a <table> element provides support for sorting by column value. Clicking the column headers will sort the table rows by that column's value. Tables must use <thead> and <th> tags for sortable functionality to work. The <th> tag defines a header cell in an HTML table.

How do you sort a list in JavaScript?

JavaScript Array sort() The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.


2 Answers

Below should do the trick:

$(function() {
  $('button').click(function() {
    var liContents = [];
    $('ul li').each(function() {
      liContents.push(parseInt($(this).text(), 10));
    });
    liContents.sort(numOrdDesc);
    $('ul li').each(function() {
      $(this).text(liContents.pop());
    });
  });
});

function numOrdDesc(a, b) {
  return (b - a);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>20</li>
  <li>10</li>
  <li>5</li>
  <li>3</li>
  <li>32</li>
  <li>25</li>
  <li>6</li>
  <li>12</li>
  <li>8</li>
</ul>

<button>Sort</button>
like image 166
Selvakumar Arumugam Avatar answered Oct 18 '22 12:10

Selvakumar Arumugam


var li = $('ul li');
li.sort(function(a, b) {
    if(parseInt($(a).text()) > parseInt($(b).text()))
        return 1;
    else return -1;
});
$('ul').empty().html(li);
like image 20
thecodeparadox Avatar answered Oct 18 '22 14:10

thecodeparadox