Define fixed sort order in JavaScript

我是研究僧i 提交于 2020-07-05 04:32:10

问题


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


回答1:


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);
});



回答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>');


来源:https://stackoverflow.com/questions/34631908/define-fixed-sort-order-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!