# sort array

## Sorting Arrays in JavaScript

Sorting is a fundamental operation in programming. In JavaScript, we can sort arrays using the built-in `sort()`

method.

### Syntax

The `sort()`

method has the following syntax:

`array.sort([compareFunction])`

The `compareFunction`

parameter is optional. It is a function that defines the sort order. If omitted, the array is sorted in ascending order by default.

### Examples

Let's see some examples of sorting arrays in JavaScript.

#### Sorting an Array of Strings

Suppose we have an array of names:

`const names = ["Alice", "Bob", "Charlie", "David"];`

We can sort this array in ascending order as follows:

`names.sort(); // ["Alice", "Bob", "Charlie", "David"]`

The resulting array is sorted in alphabetical order.

#### Sorting an Array of Numbers

Suppose we have an array of numbers:

`const numbers = [5, 2, 9, 1, 7];`

We can sort this array in ascending order as follows:

`numbers.sort((a, b) => a - b); // [1, 2, 5, 7, 9]`

The `compareFunction`

parameter is a function that takes two arguments `a`

and `b`

, which are two elements of the array being sorted. The function should return a negative, zero, or positive value, depending on the sort order of `a`

and `b`

. In this example, we subtract `b`

from `a`

, which sorts the array in ascending order.

We can also sort the array in descending order as follows:

`numbers.sort((a, b) => b - a); // [9, 7, 5, 2, 1]`

In this case, we subtract `a`

from `b`

, which sorts the array in descending order.

#### Sorting an Array of Objects

Suppose we have an array of objects:

```
const people = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 20 }
];
```

We can sort this array by the `age`

property in ascending order as follows:

`people.sort((a, b) => a.age - b.age);`

The resulting array is sorted by age as follows:

```
[
{ name: "Charlie", age: 20 },
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 }
]
```

We can sort the array by the `name`

property in alphabetical order as follows:

`people.sort((a, b) => a.name.localeCompare(b.name));`

The resulting array is sorted by name as follows:

```
[
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 20 }
]
```

### Conclusion

Sorting arrays is an important skill in programming, and JavaScript provides a convenient `sort()`

method for this purpose. By providing a `compareFunction`

parameter, we can customize the sort order to suit our needs.