We can write a compare function to compare the property values of an object.
For example:
var cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}
];
cars.sort(function(a, b){return a.year - b.year});
Even if objects have properties of different data types, the sort() method can be used to sort the array.
But that was for comparing the number properties.
Comparing string properties is a little more complex:
var cars = [
{ type: "Volvo", year: 2016 },
{ type: "Saab", year: 2001 },
{ type: "BMW", year: 2010 },
];
cars.sort(function (a, b) {
var x = a.type.toLowerCase();
var y = b.type.toLowerCase();
if (x < y) {
return -1;
}
if (x > y) {
return 1;
}
return 0;
});
console.log(cars);
// Output
[
{ type: 'BMW', year: 2010 },
{ type: 'Saab', year: 2001 },
{ type: 'Volvo', year: 2016 }
]
Credit: w3schools
array compare examples functions objects property sorting values