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" ing first then all objects with the status "PREP" and so on.
Is there a way to do that in JavaScript?
Thanks in advance :)
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" ing first then all objects with the status "PREP" and so on.
Is there a way to do that in JavaScript?
Thanks in advance :)
Share Improve this question asked Jan 6, 2016 at 11:21 MarschiMarschi 631 silver badge6 bronze badges 3- Can you elaborate on what exactly you're trying to do? – Nick Zuber Commented Jan 6, 2016 at 11:24
-
Array.prototype.sort()
. (The documentation says it all). – Ismael Miguel Commented Jan 6, 2016 at 11:24 - try groupBy from underscoreJS. underscorejs/#groupBy OR try stackoverflow./questions/14592799/… – Vishal Rajole Commented Jan 6, 2016 at 11:27
2 Answers
Reset to default 16It's a pretty simple parison operation using a standard .sort()
callback:
var preferredOrder = ['END', 'ERR', ..];
myArray.sort(function (a, b) {
return preferredOrder.indexOf(a.status) - preferredOrder.indexOf(b.status);
});
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>');