Advertisement

Javascript sort array

 In JavaScript, you can use the sort() method to sort the elements of an array. By default, the sort() method sorts the elements in ascending order, but you can also provide a custom sorting function to specify a different sort order.


Here is an example of how to use the sort() method to sort an array of numbers in ascending order:

let numbers = [3, 1, 2];

numbers.sort();

console.log(numbers); // Output: [1, 2, 3]{codeBox}

You can also use the sort() method to sort an array of strings in alphabetical order:
let words = ['cat', 'apple', 'dog'];

words.sort();

console.log(words); // Output: ['apple', 'cat', 'dog']{codeBox}
If you want to sort the array in descending order, you can provide a custom sorting function that compares the elements and returns a value less than 0 if the first element should come before the second element, a value greater than 0 if the first element should come after the second element, and 0 if the elements are equal.

Here is an example of how to use a custom sorting function to sort an array of numbers in descending order:
let numbers = [3, 1, 2];

numbers.sort(function(a, b) {
  return b - a;
});

console.log(numbers); // Output: [3, 2, 1]{codeBox}