6

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 :)

Marschi
  • 63
  • 6
  • Can you elaborate on what exactly you're trying to do? – Nick Zuber Jan 06 '16 at 11:24
  • [`Array.prototype.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort). (The documentation says it all). – Ismael Miguel Jan 06 '16 at 11:24
  • try groupBy from underscoreJS. http://underscorejs.org/#groupBy OR try http://stackoverflow.com/questions/14592799/object-array-group-by-an-element – Vishal Rajole Jan 06 '16 at 11:27

2 Answers2

14

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);
});
deceze
  • 510,633
  • 85
  • 743
  • 889
2

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>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392