To sort array of objects by string property value with JavaScript, we use the sort
method.
For instance, we write
const compare = (a, b) => {
if (a.lastName < b.lastName) {
return -1;
}
if (a.lastName > b.lastName) {
return 1;
}
return 0;
};
const sorted = objs.sort(compare);
to call sort
with the compare
function to return a number determining the order of the items.
We return -1 if a.lastName
is before b.lastName
.
We return 1 if a.lastName
is after b.lastName
.
And we return 0 otherwise.
An array with the values sorted by the lastName
property of each object is returned.