DEV Community

fara0197
fara0197

Posted on

Array.prototype.sort()

Syntax:
arr.sort(function)

Description:
The sort method in javascript, allows you to arrange the elements in an array in place.

By default, the sort method arranges the elements from smallest to the largest value, and alphabetic order.

Example 1: Strings
This example takes an array of names. By using the sort method, the names will be arranged in alphabetic order.
Image description
Output:
Image description

Example 2: Numbers
This example takes an array of grades, and arranges the numbers from lowest to the highest value.Image description
It is important to note that only the first instance of a value will be sorted. For example, if the array has a value that is a double digit, the first number will only be sorted. In this example, those values are 23 and 51.

Image description

To get an accurate output, we would use a compare function.

Image description

The sort method takes a comparison function as a parameter.
This compares the values in the array, by subtracting one value to the next value. It decides which value will go to the right of the array (the higher numbers) or the left of the array(the lower numbers).

The will allow us to get an accurate output

Image description

Top comments (0)