How to sort a JSON Object Array

 Sorting a JSON Object Array

You might have use sort() method to sort an array, but several time we might have requirement to sort a JSON object array based on a key attribute. In the below example we will learn how to sort a JSON object array.

Code -


function GetSortOrder(prop) {    

    return function(a, b) {    

        if (a[prop] > b[prop]) {    

            return 1;    

        } else if (a[prop] < b[prop]) {    

            return -1;    

        }    

        return 0;    

    }    

}


$.each(data, function(index, value)

                        {                               

                                theArray.push(

                                {

                                        "finalProductsOnSubmit": value.Products,

                                        "finalsubProductsOnSubmit": value.SubProduct,

                                        "finalattributesOnSubmit": value.Attributes,

                                        "finalregionOnSubmit": value.Region,

                                        "finalcountryOnSubmit": value.Country,

                                        "finalvalueOnSubmit": value.Value,

                                        "finalvalueCat": value.Value_x0020_Category

                                });                                 

                        });


theArray.sort(GetSortOrder("finalcountryOnSubmit"));


The above code will sort the JSON Object array based on "finalcountryOnSubmit" value. You may implement same in any of your BAU requirement.


Comments

Popular posts from this blog

How to Customize exported excel's cell background color in Datatables

Customizing SharePoint list and implementing Quick search using jQuery

Populate dropdown using jquery ajax in SharePoint