Real-world data rarely comes as a plain array of numbers — it’s usually an array of objects, like a list of users, products, or orders, and you need to sort it by one of their properties. JavaScript’s built-in Array.prototype.sort() handles this once you give it the right comparator function.

JavaScript Program to Sort an Array of Objects by a Numeric Property

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

const sortedByAge = [...users].sort((a, b) => a.age - b.age);

console.log(sortedByAge);

Output:

[ { name: 'Bob', age: 22 }, { name: 'Alice', age: 28 }, { name: 'Charlie', age: 35 } ]


JavaScript Program to Sort an Array of Objects by a String Property

Sorting by a string property needs localeCompare() instead of subtraction, since you can’t subtract two strings.

const sortedByName = [...users].sort((a, b) => a.name.localeCompare(b.name));

console.log(sortedByName.map(u => u.name));

Output:

[ 'Alice', 'Bob', 'Charlie' ]

Note the spread [...users] before calling sort() — sort() mutates the original array in place, so copying it first avoids accidentally reordering data elsewhere in your program that still expects the original order. A numeric comparator (a.prop - b.prop) versus a string comparator (a.prop.localeCompare(b.prop)) covers the vast majority of real-world sorting needs.