Sort Array of strings in javascript

  The following function can be used to sort an array of strings in descending order.

  /**
     * Sort array in descending order
     * @param {*} arr array to be sorted
     * @returns sorted array
     */
    function sortDescending(arr) {
        arr.sort((a, b) => b.localeCompare(a));
        return arr;
    }

 

The following function can be used to sort an array of strings in ascending order.

    /**
     * Sorts an array of strings in ascending order.
     * @param {Array} arr - The array of strings to be sorted.
     * @returns {Array} The sorted array.
     */
    function sortAscending (arr){
        return arr.slice().sort(function (a, b) {
            return a.localeCompare(b);
        });
    }

Leave a comment

Your email address will not be published. Required fields are marked *