How to sort an array of objects by string property value

Sorting of an array of objects by using the string property value in Javascript can easily be achieved using the default sort() method available in Javascript. Here is a working example showing how to sort an array of objects by the string property value.

Also Read: How to remove a particular element from an array in Javascript.

Assume you want to sort the following array in javascript using its string property value.

const list = [
  { color: 'white', size: 'XXL' },
  { color: 'red', size: 'XL' },
  { color: 'black', size: 'M' }

Now, we can use the sort() method of Array, which takes a callback function, which takes as parameters 2 objects contained in the array (which we call a and b):

list.sort((a, b) => (a.color > b.color) ? 1 : -1)

When the method returns 1, the function sort() that the object b takes precedence in sorting over the object a. for performing just the opposite of this, we will return -1.

So, this is all about sorting an array of the object by the string property value. Thanks for reading!

Leave a Comment