![](/img/trans.png)
[英]JavaScript array of objects sort by specific property and then group by custom priority values
[英]Javascript sort array of objects using array of priority
我有這個對象數組:
var eventList = [
{
eventName: "abc",
status: "completed"
},
{
eventName: "def",
status: "live"
},
{
eventName: "ghi",
status: "live"
},
{
eventName: "jkl",
status: "upcoming"
},
]
我想使用特定鍵的優先級數組對這些對象數組進行排序,例如["live", "upcoming", "completed"]
表示狀態,這意味着所有實時事件首先出現,然后是即將到來的,然后是完成的。 互聯網上的答案似乎只能使用鍵對數組對象進行升序或降序排序。 我該如何處理?
您可以使用帶有排序數組的Array.prototype.sort()
方法來完成。
const eventList = [ { eventName: 'abc', status: 'completed', }, { eventName: 'def', status: 'live', }, { eventName: 'ghi', status: 'live', }, { eventName: 'jkl', status: 'upcoming', }, ]; const order = ['live', 'upcoming', 'completed']; eventList.sort((x, y) => order.indexOf(x.status) - order.indexOf(y.status)); console.log(eventList);
如果您想在排序時更快地進行索引搜索,可以使用Map Object
。
const eventList = [ { eventName: 'abc', status: 'completed', }, { eventName: 'def', status: 'live', }, { eventName: 'ghi', status: 'live', }, { eventName: 'jkl', status: 'upcoming', }, ]; const order = ['live', 'upcoming', 'completed']; const map = new Map(); order.forEach((x, i) => map.set(x, i)); eventList.sort((x, y) => map.get(x.status) - map.get(y.status)); console.log(eventList);
您可以通過首先根據 status 對數組進行分組,然后在 order 數組上使用status
.flatMap()
來執行此操作,而無需對線性時間復雜度進行排序。 對於有序數組中的每個值,您可以從 O(1) 中的分組中獲取分組值(即:立即),以及 map 這些分組對象。 當您使用 flatMap 時,這些分組對象將被展平為結果數組:
const eventList = [ { eventName: "abc", status: "completed" }, { eventName: "def", status: "live" }, { eventName: "ghi", status: "live" }, { eventName: "jkl", status: "upcoming" }, ]; const order = ["live", "upcoming", "completed"]; const grouped = eventList.reduce( (map, o) => map.set(o.status, (map.get(o.status) || []).concat(o)), new Map ); const result = order.flatMap(status => grouped.get(status) || []); console.log(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.