Example 1: Sort Array by Property Name
Output
[{name: "Jack", age: 25},
{name: "John", age: 24},
{name: "Sara", age: 24}]
In the above program, the sort() method is used to sort an array by the name property of its object elements.
The sort() method sorts its elements according to the values returned by a custom sort function (compareName in this case).
Here,
- The property names are changed to uppercase using the
toUpperCase()method. - If comparing two names results in 1, then their order is changed.
- If comparing two names results in -1 or 0, then their order is left as is.
Example 2: Sort Array by Property Age
Output
[{name: "John", age: 22},
{name: "Sara", age: 24},
{name: "Jack", age: 27}]
In the above program, the sort() method is used to sort an array element by the age property.
To compare the age property of two objects, we can simply subtract them.
- If their difference is a negative value, their order is changed.
- If their difference is a positive value, the order is left as is.