js sort array of numbers code example
Example 1: sorting array from highest to lowest javascript
let numbers = [5, 13, 1, 44, 32, 15, 500]
let lowestToHighest = numbers.sort((a, b) => a - b);
let highestToLowest = numbers.sort((a, b) => b-a);
Example 2: javascript sort function
var points = [40, 100, 1, 5, 25, 10];
points.sort((a,b) => a-b)
Example 3: javascript sort numbers
var numArray = [140000, 104, 99];
numArray.sort(function(a, b) {
return a - b;
});
Example 4: javascript sort array in ascending order
function myFunction() {
points.sort(function(a, b){return a-b});
document.getElementById("demo").innerHTML = points;
}
Example 5: sorting array of numbers in javascript
var arr = [23, 34343, 1, 5, 90, 9]
var sortedArr = [];
arr.forEach(x => {
if (sortedArr.length == 0)
sortedArr.push(x)
else {
if (sortedArr[0] > x) sortedArr.unshift(x)
else if (sortedArr[sortedArr.length - 1] < x) sortedArr.push(x)
else sortedArr.splice(sortedArr.filter(y => y < x).length, 0, x)
}
})
console.log(sortedArr);
console.log(arr.sort((a,b)=>{
return a-b;
}));
Example 6: sort numbers in array javascript
function sortNumber(a, b) {
return a - b;
}
Arr.sort(sortNumber);