sort aphabetically in javascript

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.tsx
const fruits = ['banana', 'orange', 'apple', 'mango'];

fruits.sort(); // sorts the elements alphabetically

console.log(fruits); // Output: ['apple', 'banana', 'mango', 'orange']
180 chars
6 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.tsx
const numbers = [10, 5, 8, 1, 7];

// sorting the numbers in ascending order
numbers.sort((a, b) => a - b);

console.log(numbers); // Output: [1, 5, 7, 8, 10]
159 chars
7 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