Marky D
Marky D

Reputation: 1

Sorting an array of JavaScript objects by sub array property/value

I have the following data being returned from a server (the structure of this data is something that I do not have control over)...

var data = {
    "TrackingResults": [
        {
            "Name": "Pack One",
            "Products": {
                "Product": [
                    {
                        "ProductName": "Soccer Ball"
                    },
                    {
                        "ProductName": "Tennis Racket"
                    },
                    {
                        "ProductName": "Gold Putter"
                    }
                ]
            },
            "status": "Despatched",
            "Location": "Alabama",
            "Type": "Parcel"
        },
        {
            "Name": "Pack Two",
            "Products": {
                "Product": [
                    {
                        "ProductName": "Backet Ball Hoop"
                    },
                    {
                        "ProductName": "Base Ball Glove"
                    }
                ]
            },
            "status": "Despatched",
            "Location": "Florida",
            "Type": "Parcel"
        }
    ]
};

I would like to be able to sort each Tracking Result by the first Product Name. I can't find any code that will sort by a sub array property/value.

Upvotes: 0

Views: 534

Answers (2)

Mior
Mior

Reputation: 831

You need to write it manually like: (with the hint on localeCompare from meskobalazs's comment)

var result = data.TrackingResults.sort(function(a,b){
    return a.Products.Product[0].ProductName.localeCompare(b.Products.Product[0].ProductName)
});

This should work for sorting TrackingResults

Upvotes: 0

meskobalazs
meskobalazs

Reputation: 16031

You should use the Array.sort method with a custom comparator function:

var resultsComparator = function (res1, res2) {
    var prod1 = res1.Products.Product[0].ProductName;
    var prod2 = res2.Products.Product[0].ProductName;
    return prod1.localeCompare(prod2);
}

This way the ordering is based on the current locale of the web browser. You just pass the function to the sort method:

data.TrackingResults.sort(resultsComparator);

Upvotes: 2

Related Questions