Use the Compare Function in the sort() method or Loops to sort numbers in JavaScript. Using the alone sort() method will get a weird result, there is numeric order.
var numArray = [140000, 104, 99]; numArray = numArray.sort(); console.log(numArray)// [ 104, 140000, 99 ]
This is because the array got sorted in lexicographical order (that is, alphabetically), so each integer actually got coerced into a string type.
Solution
sort(function(a, b){return a-b});
JavaScript sort numbers
Simple example code Sort Numeric Array using JavaScript. Sort numbers in ascending and descending order.
<!DOCTYPE html>
<html>
<body>
<script>
//Ascending
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
console.log(points)
//descending
var arr = [100, 15, 20, 45, 30, 1];
arr.sort(function(a, b){return b-a});
console.log(arr);
</script>
</body>
</html>
Output:
You can also use loops to sort the array elements. Here is a bubble sort (simple sorting technique) to sort the array of elements in ascending order.
<script>
// Sorting function
function Numeric_sort(ar) {
var i = 0, j;
while (i < ar.length) {
j = i + 1;
while (j < ar.length) {
if (ar[j] < ar[i]) {
var temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
}
j++;
}
i++;
}
}
var arr = [100, 15, 20, 45, 30, 1];
Numeric_sort(arr)
console.log(arr);
</script>
Output: [ 1, 15, 20, 30, 45, 100 ]
How to sort an array of integers correctly
Answer: By default, the sort() method sorts elements alphabetically. To sort numerically just add a Sort Compare Function that handles numeric sorts.
This compares functions for arrays that don’t contain Infinity or NaN. (Because Infinity - Infinity
is NaN, not 0).
<script>
var numArray = [100, 104, 99];
numArray.sort(function(a, b) {
return a - b;
});
console.log(numArray);
</script>
Output: [ 99, 100, 104 ]
Do comment if you have any doubts or suggestions on this JS number topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version