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:
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.
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.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}