Sort a numeric array from small to largest in jquery

numArray.sort((a, b) => a – b); // For ascending sort numArray.sort((a, b) => b – a); // For descending sort

But above code will work only on ES6,6 supporting browser If you want to work in Old browser as well use below code.

 
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array Sort</h2>

<p>The sort() method sorts an Numeric array .</p>

<button onclick=”myFunction()”>Try it</button>

<p id=”demo”></p>

var array1 = [1, 30, 4, 21,0,12,21,11,456];
function myFunction() {
array1.sort(compareNumbers);
document.getElementById(“demo”).innerHTML = array1;
}
function compareNumbers(a, b)
{
return a – b;
}

</body>
</html>

 

Leave a comment