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 :)
Definition and Usage. The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.
JavaScript Array sort() Method sort() method is used to sort the array in place in a given order according to the compare() function. If the method is omitted then the array is sorted in ascending order.
In order to sort a list in numerical order, the Array. prototype. sort() method needs to be passed a comparison function. To sort the array numerically in ascending order, That comparison function should return the difference between the two numbers.
To define custom sort function, you need to compare first value with second value. If first value is greater than the second value, return -1. If first value is less than the second value, return 1 otherwise return 0. The above process will sort the data in descending order.
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);
});
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>');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With