Skip to main content

Sort an Array of Objects using JavaScript

Overview

Sorting an array of objects based on a specific property is a frequent necessity in JavaScript, especially when dealing with data display and manipulation. This snippet provides a method to sort an array of objects by a given property, either in ascending or descending order.

Code

Sorting Function

function sortArrayByProperty(array, property, order = "ascending") {
return array.sort((a, b) => {
let comparison = 0;
if (a[property] > b[property]) {
comparison = 1;
} else if (a[property] < b[property]) {
comparison = -1;
}
return order === "ascending" ? comparison : -comparison;
});
}

Example Usage

Sort Array of Objects by a Property

const users = [
{ name: "Alice", age: 30 },
{ name: "Bob", age: 24 },
{ name: "Clara", age: 28 },
];

console.log("Sorted by age (ascending):", sortArrayByProperty(users, "age"));
console.log(
"Sorted by name (descending):",
sortArrayByProperty(users, "name", "descending")
);

Code Description

The sortArrayByProperty function is designed to sort an array of objects:

  • Purpose: Sorts an array of objects based on a specified property. It can sort in both ascending and descending order.
  • Implementation: Uses the array sort method with a custom comparison function, which compares the properties of the objects.
  • Parameters:
    • array: The array to sort.
    • property: The property to sort by.
    • order: Optional. Specifies the sorting order ('ascending' or 'descending'). Default is 'ascending'.
  • Return Value: The sorted array.

This function is highly useful for organizing data, particularly in user interfaces where sorting data makes it more accessible and readable.

References