Sort Array Of Objects By Int Property Value In Javascript

Sort Array Of Objects By Int Property Value In Javascript

4 min read Jun 20, 2024
Sort Array Of Objects By Int Property Value In Javascript

Sort Array of Objects by Int Property Value in JavaScript

Sorting arrays of objects is a common task in JavaScript development. In this article, we'll explore how to sort an array of objects based on the value of an integer property using the sort() method.

Understanding the sort() Method

The sort() method in JavaScript is used to rearrange the elements of an array in place. By default, it sorts the array lexicographically, treating elements as strings. To sort numerically, we need to provide a custom comparison function.

The Comparison Function

The comparison function is passed as an argument to the sort() method. It takes two arguments, a and b, representing two elements from the array. The function should return:

  • A negative number if a should come before b.
  • A positive number if a should come after b.
  • Zero if a and b are considered equal.

Sorting by Int Property

Let's say we have an array of objects called users, where each object has an age property:

const users = [
  { name: "Alice", age: 30 },
  { name: "Bob", age: 25 },
  { name: "Charlie", age: 35 },
  { name: "David", age: 28 }
];

To sort this array by age in ascending order, we can use the following code:

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

Explanation:

  1. We call the sort() method on the users array.
  2. We provide a comparison function that subtracts the age property of b from the age property of a.
  3. If a.age is smaller than b.age, the result is negative, placing a before b.
  4. If a.age is greater than b.age, the result is positive, placing a after b.
  5. If a.age is equal to b.age, the result is zero, leaving their relative positions unchanged.

After sorting, the users array will be:

[
  { name: "Bob", age: 25 },
  { name: "David", age: 28 },
  { name: "Alice", age: 30 },
  { name: "Charlie", age: 35 }
]

Sorting in Descending Order

To sort in descending order, simply reverse the comparison logic:

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

This will place the users with higher ages first.

Conclusion

Sorting an array of objects by an integer property in JavaScript is straightforward using the sort() method with a custom comparison function. By understanding the logic of the comparison function, you can easily customize the sorting behavior to meet your specific needs.