To sort an array of objects by property values in JavaScript, you can use the “sort()” method with a “custom comparison function” that compares the values of the desired property.
Example
const myArray = [
{ name: 'Niva', age: 25 },
{ name: 'Khushi', age: 30 },
{ name: 'Millie', age: 20 }
];
myArray.sort((a, b) => a.age - b.age);
console.log(myArray);
Output
[
{ name: 'Millie', age: 20 },
{ name: 'Niva', age: 25 },
{ name: 'Khushi', age: 30 }
]
In this code, the sort() method is called on the myArray array with a comparison function as an argument.
The comparison function takes two objects, a and b, as arguments and subtracts b.age from a.age.
This returns a negative value if a.age is less than b.age, zero if they are equal, and a positive value if a.age is greater than b.age.
This comparison function causes the sort() method to sort the array in ascending order of age.
The sort() method modifies the original array in place, so the sorted array is the same as the original array.
If you don’t want to modify the original array, you can make a copy of it first using the slice() method like this:
let myArray = [
{ name: 'Niva', age: 25 },
{ name: 'Khushi', age: 30 },
{ name: 'Millie', age: 20 }
];
let sortedArray = myArray.slice().sort((a, b) => a.age - b.age);
console.log(myArray);
console.log("After sorting...")
console.log(sortedArray);
Output
[
{ name: 'Niva', age: 25 },
{ name: 'Khushi', age: 30 },
{ name: 'Millie', age: 20 }
]
After sorting...
[
{ name: 'Millie', age: 20 },
{ name: 'Niva', age: 25 },
{ name: 'Khushi', age: 30 }
]
In this code example, the slice() method is called on the myArray array to create a shallow copy of it, and the sort() method is called on the copy to sort it. The original myArray array is left unchanged.

Niva Shah is a Software Engineer with over eight years of experience. She has developed a strong foundation in computer science principles and a passion for problem-solving.