JavaScript: Sort an array of objects by a string property

Date: 2019-06-03 | javascript | array | sort | tutorial |


I've got an array of objects that I'd like to be sorted by a particular property. How do I do this?


Let's say that you have an array of objects with structure like:

    text: string;
    value: string;

And let's say that you would like all of these objects sorted in the resulting array by text, not by value. You do this by:

let myArray = [];
        text: "1",
        value: "IShouldBeFirst"
        text: "3",
        value: "IShouldBeThird"
        text: "2",
        value: "IShouldBeSecond"

// this is the sorting stuff
    (a, b) =>
    a.text === b.text
        ? 0
        : a.text > b.text
            ? 1
            : -1);

for(let element of myArray) {
    Expected result:
    * "IShouldBeFirst"
    * "IShouldBeSecond"
    * "IShouldBeThird"

The way this works is that Array.sort takes in two elements a and b and expects you to write a comparator with return values either negative, positive, or zero in order to determine which element goes first. In order to sort by our property, we simply pass in a comparator that only compares that property.

Read more about Array.sort on GeeksforGeeks

did this help?

I regularly post about tech topics I run into. You can get a periodic email containing updates on things I've built by subscribing here

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.