JavaScript(JS) array method - sort

https‮w//:‬ww.theitroad.com

The sort() method in JavaScript is used to sort the elements of an array in place (i.e., it modifies the original array) and return the sorted array.

By default, the sort() method sorts the elements of an array in ascending order according to their Unicode values. However, you can provide a function as an argument to the sort() method to specify your own sorting criteria.

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

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

In this example, we have an array fruits containing the strings ["banana", "apple", "orange", "grape"]. We use the sort() method to sort the elements of the array in alphabetical order.

The sort() method sorts the elements of the array in ascending order according to their Unicode values. In this case, the strings are sorted in alphabetical order, so the array becomes ["apple", "banana", "grape", "orange"].

We store the sorted array back into the variable fruits. We then log fruits to the console using console.log(fruits). The output is ["apple", "banana", "grape", "orange"], which is the sorted array.

Here's an example of how to use the sort() method with a function to sort an array of numbers in descending order:

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

In this example, we have an array numbers containing the numbers [5, 3, 8, 1, 2]. We use the sort() method with a function to sort the elements of the array in descending order.

We pass a function to the sort() method, which takes two arguments a and b. The function returns a negative number if a is less than b, a positive number if a is greater than b, and zero if a and b are equal. By returning b - a, we are sorting the elements of the array in descending order.

The sort() method sorts the elements of the array in descending order, so the array becomes [8, 5, 3, 2, 1].

We store the sorted array back into the variable numbers. We then log numbers to the console using console.log(numbers). The output is [8, 5, 3, 2, 1], which is the sorted array.