# Sort an array of objects by a property value in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Jul 12, 2022, updated Jun 10, 2023. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-sort-array-of-objects

> A short guide to learning how to sort an array of objects by a property value in JavaScript.

In the previous article, we explored how to [sort an object's properties](https://attacomsian.com/blog/javascript-sort-object) by their values in JavaScript. Now let's discover how to sort an array of objects by a specific property value in JavaScript.

Let's consider an array of users with their names and ages:

```javascript
const users = [
  { name: 'John Deo', age: 23 },
  { name: 'Mike Datson', age: 21 },
  { name: 'Alex Kate', age: 45 }
]
```

We can sort these users based on either their `name` or `age` using the `sort()` method provided by JavaScript arrays.

The `sort()` method also accepts a callback function, which allows us to implement a custom comparator. This callback function takes two parameters representing the elements of the array to be compared at any given time:

```javascript
const sorted = users.sort((a, b) => (a.name > b.name ? 1 : a.name < b.name ? -1 : 0))
console.log(sorted)
```

In the comparison, we return `1`, `0`, or `-1` to indicate the result. If `1` is returned, it means `a` is considered greater than `b`. `0` indicates equality, and `-1` signifies that `b` is considered lesser than `a`.

The resulting output will be:

```javascript
[
  { name: 'Alex Kate', age: 45 },
  { name: 'John Deo', age: 23 },
  { name: 'Mike Datson', age: 21 }
]
```

> **Note:** When comparing strings, uppercase and lowercase letters have different weights. For example, the lowercase letter `a` takes precedence over the uppercase letter `A`. Therefore, it is advisable to either convert strings to [lowercase or uppercase](https://attacomsian.com/blog/javascript-string-uppercase-lowercase) before comparison.

To account for both lowercase and uppercase letters, let's update our callback function:

```javascript
const sorted = users.sort((a, b) => (a.name.toLowerCase() > b.name.toLowerCase() ? 1 :
a.name.toLowerCase() < b.name.toLowerCase() ? -1 : 0))
```

Similarly, we can also sort users based on their `age`. Since `age` is an integer, the callback function can be simplified as follows:

```javascript
const sorted = users.sort((a, b) => a.age - b.age)
console.log(sorted)
```

After sorting by `age`, the `sorted` array will be:

```javascript
[
  { name: 'Mike Datson', age: 21 },
  { name: 'John Deo', age: 23 },
  { name: 'Alex Kate', age: 45 }
]
```
