How To Sort An Array In Javascript
In This Javascript Tutorial we will See How To Sort An Array Of Numbers And Array Of String, ASC Or DESC Order In JS And Netbeans Editor .
Project Source Code:
<!DOCTYPE html>
<html>
<head>
<title>Javascript: Sorting Array</title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<p id="arr"></p>
<p id="arrS"></p>
<p id="arrDesc"></p>
<script>
var arrL = ["C++","Java","C#","Swift","Angular","Javascript","Android","Php"],
arrN = [33,7,27,81,11,0,61,17,20,9,44];
document.getElementById("arr").innerHTML = arrN;
//document.getElementById("arrS").innerHTML = arrN.sort(function(a,b){return a-b;});
// asc order
arrN.sort(function(a,b){
if(a < b)
return -1;
else if(a > b)
return 1;
else
return 0;
});
// desc order , asc order
document.getElementById("arrS").innerHTML = arrN;
// desc order
/* arrN.sort(function(a,b){
if(a > b)
return -1;
else if(a < b)
return 1;
else
return 0;
});*/
document.getElementById("arrDesc").innerHTML = arrN.reverse();
</script>
</body>
</html>
OUTPUT: