Sort() is a function that sorts an array in alphabetical order.
const alphabets = ["C", "B", "A", "D"];
alphabets.sort();
console.log(alphabets);
[ 'A', 'B', 'C', 'D' ]
const alphabets = ["C", "B", "A", "D"];
alphabets.sort();
alphabets.reverse();
console.log(alphabets);
[ 'D', 'C', 'B', 'A' ]
To determine the order, the sort() function converts items to strings and compares them.
let numbers = [0, 1 , 3, 2, 11, 34, 20];
numbers.sort();
console.log(numbers);
[ 0, 1, 11, 2, 20, 3, 34 ]
To sort numbers we can use following method
let numbers = [0, 1 , 3, 2, 11, 34, 20];
numbers.sort( function( a , b){
if(a > b) return 1;
if(a < b) return -1;
return 0;
});
console.log(numbers);
[ 0, 1, 2, 3, 11, 20, 34 ]