How to sort an array of objects by a property value in JavaScript
byThere is always a need to sort an array. What if array consists of custom objects? How do we sort array of custom objects by a property value? Let us find out!
const array = [
{ name: ‘John’, order: ‘2’ },
{ name: ‘Jack’, order: ‘1’ },
{ name: ‘James’, order: ‘10’ }
]
First way:
function compare(a, b) {
if (a.order < b.order)
return -1;
if (a.order > b.order)
return 1;
return 0;
}
newArray = array.sort(compare);
Second way:
newArray = array.sort((a, b) => (a.order > b.order) ? 1 : -1)