在JavaScript中定义固定的排序顺序 [英] Define fixed sort order in JavaScript
本文介绍了在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"
}
]
}
现在,我想设置一个固定的排序顺序,例如所有状态为"END"的对象首先出现,然后是状态为"PREP"的所有对象,依此类推.
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.
有没有办法用JavaScript做到这一点?
Is there a way to do that in JavaScript?
先谢谢您了:)
推荐答案
这是使用标准.sort()
回调的非常简单的比较操作:
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);
});
这篇关于在JavaScript中定义固定的排序顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文