One way to sort an array of strings alphabetically is to use the sort()
method. By default, the sort()
method sorts elements alphabetically, as strings.
Here's an example:
index.tsx180 chars6 lines
In this example, fruits
is an array of strings, and we use the sort()
method to sort its elements alphabetically. The sorted array is then outputted to the console.
Note that sort()
sorts elements as strings, so numbers are sorted as strings as well. If you need to sort numbers or non-string elements in a custom way, you can pass a compare function into the sort()
method, like so:
index.tsx159 chars7 lines
In this example, we sort an array of numbers in ascending order by passing a compare function into the sort()
method. The compare function subtracts the second value from the first, which sorts the numbers in ascending order.
gistlibby LogSnag