Categories
JavaScript Answers

How to sort array of objects by string property value with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *