JavaScript - sort() method

revision:


Category : array

The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

The time and space complexity of the sort cannot be guaranteed as it depends on the implementation.

To sort the elements in an array without mutating the original array, use toSorted().

Syntax :

        array.sort()
        array.sort(compareFn)
    

Parameters:

compareFn : optional. A function that defines the sort order. The return value should be a number whose sign indicates the relative order of the two elements: negative if "a: is less than "b", positive if "a" is greater than "b", and zero if they are equal. NaN is treated as 0. The function is called with the following arguments:

a : the first element for comparison. Will never be undefined.
b : the second element for comparison. Will never be undefined.
If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value.

Examples:

            const months = ['March', 'Jan', 'Feb', 'Dec'];
            months.sort();
            console.log(months);
            // Expected output: Array ["Dec", "Feb", "Jan", "March"]
            const array1 = [1, 30, 4, 21, 100000];
            array1.sort();
            console.log(array1);
            // Expected output: Array [1, 100000, 21, 30, 4]
        

Practical examples

example: creating, displaying, and sorting an array.

code:
                    <div>
                        <p id="sort-1"></p>
                        <p id="sort-2"></p>
                        <p id="sort-3"></p>
                        <p id="sort-4"></p>
                        <p id="sort-5"></p>
                        <p id="sort-6"></p>
                        <p id="sort-7"></p>
                        <p id="sort-8"></p>
                        <p id="sort-9"></p>
                        <p id="sort-10"></p>
                        <p id="sort-11"></p>
                        <p id="sort-12"></p>
                        <p id="sort-13"></p>
            
                    </div>
                    <script>
                        const stringArray = ["Blue", "Humpback", "Beluga"];
                        const numberArray = [40, 1, 5, 200];
                        const numericStringArray = ["80", "9", "700"];
                        const mixedNumericArray = ["80", "9", "700", 40, 1, 5, 200];
                        document.getElementById("sort-1").innerHTML = "string array : " + JSON.stringify(stringArray);
                        document.getElementById("sort-2").innerHTML = "number array : " + JSON.stringify(numberArray);
                        document.getElementById("sort-3").innerHTML = "numericString array : " + JSON.stringify(numericStringArray);
                        document.getElementById("sort-4").innerHTML = "mixed numeric array : " + JSON.stringify(mixedNumericArray);
                        function compareNumbers(a, b) {
                        return a - b;
                        }
                        stringArray.join(); // 'Blue,Humpback,Beluga'
                        document.getElementById("sort-5").innerHTML = "string array join : " + stringArray.join();
                        stringArray.sort(); // ['Beluga', 'Blue', 'Humpback']
                        document.getElementById("sort-6").innerHTML = "string array sort : " + stringArray.sort();
                        numberArray.join(); // '40,1,5,200'
                        document.getElementById("sort-7").innerHTML = "number array join : " + numberArray.join();
                        numberArray.sort(); // [1, 200, 40, 5]
                        document.getElementById("sort-8").innerHTML = "number array sort : " + numberArray.sort();
                        numberArray.sort(compareNumbers); // [1, 5, 40, 200]
                        document.getElementById("sort-8").innerHTML = "number array sort compare numbers : " + 
                        numberArray.sort(compareNumbers);
                        numericStringArray.join(); // '80,9,700'
                        document.getElementById("sort-9").innerHTML = "numericString array join : " + 
                        numericStringArray.join();
                        numericStringArray.sort(); // ['700', '80', '9']
                        document.getElementById("sort-10").innerHTML = "numericString array sort : " + 
                        numericStringArray.sort();
                        numericStringArray.sort(compareNumbers); // ['9', '80', '700']
                        document.getElementById("sort-10").innerHTML = "numericString array sort compare numbers : " + 
                        numericStringArray.sort(compareNumbers);
                        mixedNumericArray.join(); // '80,9,700,40,1,5,200'
                        document.getElementById("sort-11").innerHTML = "mixed numeric array join : " + 
                        mixedNumericArray.join();
                        mixedNumericArray.sort(); // [1, 200, 40, 5, '700', '80', '9']
                        document.getElementById("sort-12").innerHTML = "mixed numeric array sort : " + 
                        mixedNumericArray.sort();
                        mixedNumericArray.sort(compareNumbers); // [1, 5, '9', 40, '80', 200, '700']
                        document.getElementById("sort-13").innerHTML = "mixed numeric array sort copare numbers: " + 
                        mixedNumericArray.sort(compareNumbers);
                        
                    </script>
                

example: sorting an array of objects: sort and reverse.

code:
                    <div>
                        <p id="sort-14"></p>
                        <p id="sort-15"></p>
                        <p id="sort-16"></p>
                    </div>
                    <script>
                        const fruits = [" Banana", " Orange", " Apple", " Mango"];
                        document.getElementById("sort-14").innerHTML = "original array : " + fruits;
                        document.getElementById("sort-15").innerHTML = "sorted array : " + fruits.sort();
                        fruits.reverse();
                        document.getElementById("sort-16").innerHTML = "reversed array : " + fruits;
                    </script>
                

example: find the highest and lowest value.

code:
                    <div>
                        <p id="sort-17"></p>
                        <p id="sort-18"></p>
                        <p id="sort-19"></p>
                        <p id="sort-20"></p>
                        <p id="sort-21"></p>
                        <p id="sort-22"></p>
                    </div>
                    <script>
                        const points = [40, 100, 1, 5, 25, 10];
                        document.getElementById("sort-17").innerHTML = "array : " + points;
                        // Sort the numbers in descending order:
                        points.sort(function(a, b){return b-a});
                        document.getElementById("sort-18").innerHTML = "sorted array : " + points;
                        // points[0] is now the highest value:
                        document.getElementById("sort-19").innerHTML = "highest value : " + points[0];
                        // Sort the numbers in ascending order:
                        points.sort(function(a, b){return a-b});
                        document.getElementById("sort-20").innerHTML = "sorted array : " + points;
                        // points[0] is now the lowest value:
                        document.getElementById("sort-21").innerHTML = "lowest value : " + points[0];
            
                    </script>