How to sort array of objects by string property value in JavaScript

October 12, 2022 No comments javascript arrays sorting comparison

Introduction

Sometimes, we may wish to sort array of objects by string property value in JavaScript. In this post, we'll learn how to do it.

How to sort an array of objects by string property value in JavaScript

To sort the array of objects by string property value in JavaScript we can use the sort() function:

const array = [
    {name: 'John', surname: 'Doe'},
    {name: 'Aludra', surname: 'Bernardo'},
    {name: 'Erlea', surname: 'Eyal'}
];

function compareSurnames(a, b) {
  if (a.surname < b.surname) {
    return -1;
  }
  if (a.surname > b.surname) {
    return 1;
  }
  return 0;
}

objs.sort(compareSurnames); 

// es6
array.sort((a,b) => (a.surname > b.surname) ? 1 : ((b.surname > a.surname) ? -1 : 0));

In this example, we created an array and fill it with objects that contain two properties: name and surname. Then we use the compareSurnames(a, b) function to compare each object of the array. That function returns -1 when a current object should be below the next one, 1 when the current object should be above the next one, and 0 when both objects are the same.

Next, we used the array.sort(comparator) method to sort our array using the prepared comparator function.

const array = [
    {name: 'John', surname: 'Doe'},
    {name: 'Aludra', surname: 'Bernardo'},
    {name: 'Erlea', surname: 'Eyal'}
];

array.sort((a,b) => a.name.localeCompare(b.name));

From ES6 we can use the localCompare() function that returns a number indicating whether a reference string comes before, after, or is the same as the given string in sort order.

Conclusion

In this post, we presented the best way to sort an array of objects by string property value in JavaScript.

{{ message }}

{{ 'Comments are closed.' | trans }}