Javascript - Sort Array of objects by property values

JavaScript Program to Sort Array of Objects by Property Values 




In this example, you will learn to write a JavaScript program that will sort an array of objects by property values.

To understand this example, you should have the knowledge of the following JavaScript programming topics

Example 1: Sort Array by Property Name





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


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.


Post a Comment

Previous Post Next Post