Marschi
Marschi

Reputation: 63

Define fixed sort order in JavaScript

I haven't found something in my research so I thought someone can help me here.

My problem is that I want to sort an array of objects which contains a status:

{
    "data":[
        {
            "status":"NEW"
        },
        {
            "status":"PREP"
        },
        {
            "status":"CLOS"
        },
        {
            "status":"END"
        },
        {
            "status":"ERR"
        },
        {
            "status":"PAUS"
        }
    ]
}

Now I want to set a fixed sort order like all objects with the status "END" coming first then all objects with the status "PREP" and so on.

Is there a way to do that in JavaScript?

Thanks in advance :)

Upvotes: 6

Views: 2729

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386746

You can use an object with their order values and sort it then.

var obj = { "data": [{ "status": "NEW" }, { "status": "PREP" }, { "status": "CLOS" }, { "status": "END" }, { "status": "ERR" }, { "status": "PAUS" }] };

obj.data.sort(function (a, b) {
    var ORDER = { END: 1, PREP: 2, PAUS: 3, CLOS: 4, ERR: 5, NEW: 6 };
    return (ORDER[a.status] || 0) - (ORDER[b.status] || 0);
});

document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>');

Upvotes: 2

deceze
deceze

Reputation: 522500

It's a pretty simple comparison operation using a standard .sort() callback:

var preferredOrder = ['END', 'ERR', ..];
myArray.sort(function (a, b) {
    return preferredOrder.indexOf(a.status) - preferredOrder.indexOf(b.status);
});

Upvotes: 16

Related Questions