In JavaScript, you can sort an array of objects by their property values using the Array.sort() method along with a custom sorting function.

Let’s say you have an array of objects like this:

let arrayOfObjects = [
   { name: 'John', age: 30 },
   { name: 'Alice', age: 25 },
   { name: 'Bob', age: 35 }
 ];

Sorting by a Numeric Property

If you want to sort the array of objects based on a numeric property (e.g., age), you can use a comparison function inside sort():

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

This will sort the array in ascending order based on the age property.

Sorting by a String Property

If you want to sort based on a string property (e.g., name), you can use localeCompare() inside the comparison function:

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

This will sort the array alphabetically based on the name property.

Sorting in Descending Order

To sort in descending order, you can switch a and b in the comparison function:

arrayOfObjects.sort((a, b) => b.age - a.age); // For numeric property (e.g., age)
// OR
arrayOfObjects.sort((a, b) => b.name.localeCompare(a.name)); // For string property (e.g., name)

Handling Mutable Sorting

The sort() method sorts the array in place and mutates the original array. If you want to avoid mutating the original array, you can create a new sorted array using the spread operator or Array.slice():

// Sorting by age without mutating the original array
const sortedByAge = [...arrayOfObjects].sort((a, b) => a.age - b.age);

// Sorting by name without mutating the original array
const sortedByName = arrayOfObjects.slice().sort((a, b) => a.name.localeCompare(b.name));

Support On Demand!

                                         
JavaScript