# sort method

The `sort` method sorts an array in lexicographic order and returns the already modified array. As an optional parameter, you can specify your own function for sorting.

## Syntax

`array.sort([function]);`

## Example

Let's sort an array:

`let arr = ['d', 'b', 'a', 'c']; console.log(arr.sort());`

The code execution result:

`['a', 'b', 'c', 'd']`

## Example

Let's sort an array with numbers:

`let arr = [4, 1, 7, 2]; console.log(arr.sort());`

The code execution result:

`[1, 2, 4, 7]`

## Example

Let's add numbers to an array and sort it:

`let arr = [1, 123, 2, 4, 111, 7]; console.log(arr.sort());`

As a result of the code execution, we will see that the numbers are not arranged in ascending order, but in lexicographic order, i.e. numbers are compared to each other like strings. In this case, the comparison is carried out for each character, whether the code of the first character is greater than the code of the neighboring one, etc. Result:

`[1, 111, 123, 2, 4, 7]`

## Example

Now let's sort an array using a function in which we write a condition - if the first parameter is greater than the second, then we rearrange it (for this, any positive number is in `return`). Otherwise, no rearrangement is required and we specify `0` or any negative number:

`let arr = [1, 123, 2, 4, 111, 7]; arr.sort(function(a, b) { if (a > b) { return 1; } else { return -1; } }); console.log(arr);`

The code execution result:

`[1, 2, 4, 7, 111, 123]`

## Example

Let's shorten the code for convenience in our function from the previous example:

`let arr = [1, 123, 2, 4, 111, 7]; arr.sort(function(a, b) { return a - b; }); console.log(arr);`

The code execution result:

`[1, 2, 4, 7, 111, 123]`

## Example

And now, using a function, we sort an array in descending order:

`let arr = [1, 123, 2, 4, 111, 7]; arr.sort(function(a, b) { return b - a; }); console.log(arr);`

The code execution result:

`[123, 111, 7, 4, 2, 1]`

## Example

Let's sort an array of objects by the key `'one'` in ascending order:

`let arr = [ {one: 1, two: 2}, {one: 7, two: 1}, {one: 3, two: 3} ]; arr.sort(function(a, b) { return a.one - b.one; }); console.log(arr);`

The code execution result:

`[ {one: 1, two: 2}, {one: 3, two: 3}, {one: 7, two: 1} ]`

## Example

Now let's sort an array of objects by the key `'two'`:

`let arr = [ {one: 1, two: 2}, {one: 7, two: 1}, {one: 3, two: 3} ]; arr.sort(function(a, b) { return a.two - b.two; }); console.log(arr);`

The code execution result:

`[ {one: 7, two: 1}, {one: 1, two: 2}, {one: 3, two: 3} ]`

## Example

Let's check if an array has changed after applying the `sort` method:

`let arr = ['b', 'a', 'd', 'c']; let res = arr.sort(); console.log(arr);`

The code execution result:

`['a', 'b', 'c', 'd']`

## See also

- the `filter` method
  that allows you to filter the elements of an array

← →
↑
en ru