JavaScript – Sort a String Array

To sort a string array in JavaScript, call sort() method on this string array. sort() method sorts the array in-place and also returns the sorted array, where the strings are sorted lexicographically in ascending order.

Since, the sort operation happens in-place, the order of the elements in input array are modified.

sort() method by default sorts in ascending order. To get the descending order, use reverse() method on the sorted array.

Example

In the following example, we have taken a string array in inputArr. We sort this array using sort() method and store the resulting array in sortedArr.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body>
    <pre id="output"></pre>
    <script>
        var inputArr = ['banana', 'mango', 'apple'];
        displayOutput = 'Input Array  : ' + inputArr;

        var sortedArr = inputArr.sort();
        displayOutput += '\nSorted Array : ' + sortedArr;

        document.getElementById('output').innerHTML = displayOutput;
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we learned how to sort an array of strings lexicographically using sort() method.