Tag Archives: Array Sorting Numerically in JavaScript

Sorting arrays in Javascript, Numeric sorting

If you normally sort an array, then it is sorted alphabetically or lexically.

<html>
<head>
<title>Untitled Document</title>
<script type="text/javascript">
var myarray = [10,1,100,23,2,33,4];
myarray.sort();
document.write(myarray);
</script>
</head>

<body>
</body>
</html>

The output will be : 1,10,100,2,23,33,4
Because the array myarray is sorted alphabetically.

But if you want to sort it numerically then pass a function in argument as mentioned below.

<html>
<head>
<script type="text/javascript">
var myarray = [10,1,100,23,2,33,4];
myarray.sort(function f(a,b) { return a-b; });
document.write(myarray);
</script>
</head>

<body>
</body>
</html>