techStackGuru

JavaScript Array sort method


Sort() is a function that sorts an array in alphabetical order.

Example


const alphabets = ["C", "B", "A", "D"];
alphabets.sort();

console.log(alphabets);
Output

[ 'A', 'B', 'C', 'D' ]

Array Reversal


const alphabets = ["C", "B", "A", "D"];
alphabets.sort();
alphabets.reverse();

console.log(alphabets);
Output

[ '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);
Output

[ 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);
Output

[ 0, 1, 2, 3, 11, 20, 34 ]