Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 934
Marschi Avatar asked Jan 06 '16 11:01

Marschi


People also ask

What is sort order in JavaScript?

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.

What is sort used for in JavaScript?

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.

What is the correct way to sort the numbers in ascending order JavaScript?

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.

How do you create a sort function in JavaScript?

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.


2 Answers

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);
});
like image 147
deceze Avatar answered Sep 29 '22 08:09

deceze


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>');
like image 26
Nina Scholz Avatar answered Sep 29 '22 10:09

Nina Scholz