How to sort these using Javascript or Jquery Most effectively

93 views Asked by At

How to sort these using Javascript/JQuery Most effectively

<div>6</div>
<div>2</div>
<div>7</div>
<div>5</div>
<div>9</div>
<div>4</div>
<div>8</div>
<div>1</div>
<div>3</div>
2

There are 2 answers

0
Rory McCrossan On BEST ANSWER

You can use the sort() method to organise the div elements in to the required order, then append() them to the containing element in that order. Try this:

$('div').sort(function(a, b) {
    return $(a).text() > $(b).text();
}).appendTo('body');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>6</div>
<div>2</div>
<div>7</div>
<div>5</div>
<div>9</div>
<div>4</div>
<div>8</div>
<div>1</div>
<div>3</div>

1
Tuhin On
var arr=[];
var divs =  $("div");

$.each(divs,function(index){
    if($(divs[index]).html())
    arr.push($(divs[index]).html());
});

console.log(arr.sort());