sort array with strings in alphabetical order in javascript

To sort an array with strings in alphabetical order in JavaScript, you can use the sort() method provided by the Array object. By default, the sort() method sorts the elements in an array in ascending order based on their string representations.

Here's an example of how to use the sort() method to sort an array of strings in alphabetical order:

index.tsx
const fruits = ['banana', 'orange', 'apple', 'kiwi'];

fruits.sort(); // sorts the array in alphabetical order

console.log(fruits); // ["apple", "banana", "kiwi", "orange"]
174 chars
6 lines

In this example, the sort() method is called on an array of fruits. The method sorts the elements in the array in alphabetical order and updates the original array. Finally, the sorted array is printed to the console using the console.log() method.

If you want to sort the elements in reverse alphabetical order, you can pass a custom sort function to the sort() method. Here's an example of how to sort an array of strings in reverse alphabetical order:

index.tsx
const fruits = ['banana', 'orange', 'apple', 'kiwi'];

fruits.sort(function(a, b) {
  if (a > b) {
    return -1;
  } else if (a < b) {
    return 1;
  } else {
    return 0;
  }
});

console.log(fruits); // ["orange", "kiwi", "banana", "apple"]
246 chars
14 lines

In this example, the sort() method is called with a custom sort function that compares each pair of elements in the array. The function returns -1 if the first element is greater than the second, 1 if the first element is less than the second, and 0 if the elements are equal. This custom sort function sorts the elements in reverse alphabetical order, and the sorted array is printed to the console using the console.log() method.

gistlibby LogSnag