2017-01-22 224 views
0

我有這樣的對象數組;按數組排序對象數組

var orders = [ 
    { 
    status: "pending" 
    }, 
    { 
    status: "received" 
    }, 
    { 
    status: "sent" 
    }, 
    { 
    status: "pending" 
    } 
] 

我想解決這陣基礎上status鍵的值的對象,但使對象的順序status鍵的可能值的排列順序相匹配;

var statuses = ["pending", "sent", "received"] 

因此,排序後,兩個"pending"對象將是第一,其次是"sent"對象,最後是"received"對象。

我該怎麼做?

+0

這將是更好,如果'statuses'是一個對象的索引的HashMap中,狀態名稱是屬性名稱,屬性的值是分類權重。然後你的排序比較功能可能會差異的價值。 – Pointy

回答

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)

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

0

使用Array#sort方法對象的數組排序。在哪裏使用對象來存儲密鑰的索引,這有助於避免使用方法(這是較慢的)。

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

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

0

可以用這樣的方法indexOf()排序回調之內,但更有效的是要建立第一

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