Tuesday, October 29, 2013

How to sort numbers in an array using JavaScript?


Sort numbers in an array using JavaScript:

function sortingArray()
{
var beforeSorting = [40,100,1,5,25,10];
var afterSorting;
document.getElementById("beforeSorting").innerHTML = beforeSorting;
afterSorting = beforeSorting.sort(function(a,b){return a-b});
document.getElementById("afterSorting").innerHTML = afterSorting;
}

Example:

<!DOCTYPE html>
<html>
<head>
<style>
body {
 background: #F1F1A8;
}
#beforeSorting,#afterSorting{
 font-weight:bold;
}
</style>
</head>
<body>
<div id="mainContainer">
 <div>Array before sorting is: <span id="beforeSorting"></span></div>
 <div>Array after sorting is: <span id="afterSorting"></span></div>
</div>
<script>
function sortingArray()
{
var beforeSorting = [40,100,1,5,25,10];
var afterSorting;
document.getElementById("beforeSorting").innerHTML = beforeSorting;
afterSorting = beforeSorting.sort(function(a,b){return a-b});
document.getElementById("afterSorting").innerHTML = afterSorting;
}
sortingArray();
</script>
</body>
</html>

Sample Output:


How to sort numbers in an array using JavaScript

Demo:



0 comments:

Post a Comment

Subscribe via Email