1

I have an array of objects with nested array objects.

[
    {
        "neighborhoods": [
            {
                 "origin": "Kenwood",
                 "destination": "Portage Bay"
            }
        ]
    },
    {
        "neighborhoods": [
             {
                 "origin": "First Hill",
                 "destination": "Denny-Blaine"
              }
        ]
    },
    {
        "neighborhoods": [
            {
                "origin": "Belltown",
                "destination": "Eastlake"
            }
        ]
    }
]

I want to sort the objects alphabetically based on the origin value. What is the most efficient way to do this?

1 Answers1

0

You could take the property and the object at the index zero with origin value for sorting.

var array = [{ neighborhoods: [{ origin: "Kenwood", destination: "Portage Bay" }] }, { neighborhoods: [{ origin: "First Hill", destination: "Denny-Blaine" }] }, { neighborhoods: [{ origin: "Belltown", destination: "Eastlake" }] }];

array.sort(function (a, b) {
    function getValue(o) { return o.neighborhoods[0].origin; }
    var aa = getValue(a),
        bb = getValue(b);

    return aa > bb || -(aa < bb);
});

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392