Example 1: how the sort function works javascript
const unsorted = ['d', 'd', 'h', 'r', 'v', 'z', 'f', 'c', 'g'];
const sorted = unsorted.sort();
console.log(sorted);
//["c", "d", "d", "f", "g", "h", "r", "v", "z"]
const unsortedNums = [45, 56, 3, 3, 4, 6, 7, 45, 1];
const sortedNums = unsortedNums.sort((a, b) => {
return a - b;
});
console.log(sortedNums);
//[1, 3, 3, 4, 6, 7, 45, 45, 56]
Example 2: javascript sort array in ascending order
//sorts arrays of numbers
function myFunction() {
points.sort(function(a, b){return a-b});
document.getElementById("demo").innerHTML = points;
}
Example 3: how to sort array
array sorting
Example 4: sort array javascript
let numbers = [5, 2, 8, 1, 4, 6, 3, 7]
numbers.sort() // sorts the numbers ascending: [1, 2, 3, 4, 5, 6, 7, 8]