In JavaScript, you can use the sort() method to sort an array of strings. By default, the sort() method sorts the elements of an array in alphabetical order. Here is an example:

let fruits = ["apple", "banana", "cherry"];
fruits.sort();
console.log(fruits); // ["apple", "banana", "cherry"]

In this example, the sort() method sorts the elements of the fruits array in alphabetical order, and the result is [“apple”, “banana”, “cherry”].

You can also pass a comparison function as an argument to the sort() method, to define a custom sort order. The comparison function should take two arguments, and should return a negative, zero, or positive value, depending on the order of the elements.

let numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers);  // [1,2,3,4,5]

In this example, the sort() method uses the comparison function to sort the elements of the numbers array in ascending numerical order. The function (a, b) => a – b compares two numbers and returns the difference.

You can also use sort() with the arrow function

let numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);
console.log(numbers);  // [1,2,3,4,5]

In this way, you can sort an array of strings or numbers in JavaScript using the sort() method.

Also Read:

Categorized in: