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

ADVERTISEMENT

Conclusion

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