0

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.

1
  • 2
    You will probably need to use Array.sort() with a custom Comparator ! Commented Jan 9, 2015 at 9:23

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.