Class Act

Back to the shelf

Javascript · Method · ASP.net

JSON Sort Method

A JavaScript function to sort an array of objects by any property name you choose.

Example

How to use JSON Sort Method:
After the snippet is in your project, call GetSortOrder.
GetSortOrder();

Notes

Usage: myArray.sort(GetSortOrder('value')); — replace 'value' with the property name you want to sort by.

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;
    }
}