我有一系列像这样的对象;
var orders = [
{
status: "pending"
},
{
status: "received"
},
{
status: "sent"
},
{
status: "pending"
}
]
我想根据status
键的值对这个对象数组进行排序,但是这样对象的顺序与status
键的可能值的数组顺序相匹配;
var statuses = ["pending", "sent", "received"]
因此,排序后,首先是两个"pending"
对象,然后是"sent"
对象,最后是"received"
对象。
我该怎么做?
答案 0 :(得分:0)
您可以使用sort()
和indexOf()
执行此操作。
var orders = [{
status: "pending"
}, {
status: "received"
}, {
status: "sent"
}, {
status: "pending"
}]
var statuses = ["pending", "sent", "received"]
var result = orders.sort(function(a, b) {
return statuses.indexOf(a.status) - statuses.indexOf(b.status)
})
console.log(result)

答案 1 :(得分:0)
您可以使用sort()
功能:
var statuses = ["pending", "sent", "received"];
var orders = [
{
status: "pending"
},
{
status: "received"
},
{
status: "sent"
},
{
status: "pending"
}
];
orders.sort(function(a, b) {
return statuses.indexOf(a.status) - statuses.indexOf(b.status);
});
console.log(orders);

答案 2 :(得分:0)
使用Array#sort
方法对对象数组进行排序。使用对象存储键的索引有助于避免使用Array#indexOf
方法(速度较慢)。
var orders = [{
status: "pending"
}, {
status: "received"
}, {
status: "sent"
}, {
status: "pending"
}];
var statuses = ["pending", "sent", "received"];
// generate the object which holds the index in array
// or use an object instead of array which holds the index
var index = statuses.reduce(function(obj, k, i) {
obj[k] = i;
return obj;
}, {})
console.log(
orders.sort(function(a, b) {
return index[a.status] - index[b.status];
})
)
答案 3 :(得分:0)
您可以将对象用作排序顺序的哈希表。
var orders = [{ status: "pending" }, { status: "received" }, { status: "sent" }, { status: "pending" }],
statuses = { pending: 1, sent: 2, received: 3 };
orders.sort(function (a, b) {
return statuses[a.status] - statuses[b.status];
});
console.log(orders);

答案 4 :(得分:0)
可以在排序回调中使用indexOf()
之类的方法,但更有效的方法是首先构建索引的hashmap
var statIndex = statuses.reduce(function(a,c,i){
a[c] = i;
return a
},{})
orders.sort(function(a,b){
return statIndex[a.status] - statIndex[b.status]
})