我想按狀態對任務串列進行排序,例如,狀態為“活動”的任務應按已完成的任務分組,然后應按添加順序顯示其他狀態的任務:
它應該顯示如下內容:
const taskToShows = [
{task: "task7", status: "active"},
{task: "task6", status: "active"},
{task: "task5", status: "active"},
{task: "task8", status: "completed"},
{task: "task4", status: "completed"},
{task: "task1", status: "pending"},
{task: "task2", status: "other status"},
{task: "task3", status: "progress"},
]
我的方法是使用 sort() 我可以先訂購但后來它訂購了所有任務,只需要頂部的活動和已完成的任務以及用戶添加的順序中的所有其他任務
if(this.status === 'active' || this.status === 'completed'){
this.tasksToShow = this.tasksList.sort((a, b) => (a.status.toLowerCase() >
b.status.toLowerCase()) ? 1 : (a.status.toLowerCase() === b.status.toLowerCase() )
? ((a.status > b.status) ? 0 : -1) : -1 )
}
uj5u.com熱心網友回復:
試試這個-
const taskToShows = [
{task: "task7", status: "active"},
{task: "task6", status: "active"},
{task: "task5", status: "active"},
{task: "task8", status: "completed"},
{task: "task4", status: "completed"},
{task: "task1", status: "pending"},
{task: "task2", status: "other status"},
{task: "task3", status: "progress"},
];
taskToShows.sort((a, b) => {
const arr = ['active', 'completed'];
return arr.includes(a.status) || arr.includes(b.status) ? 1 : -1;
});
console.log(taskToShows);
.as-console-wrapper{min-height: 100%!important; top: 0}
uj5u.com熱心網友回復:
- 使用
Array#reduce,迭代在陣列上而更新Map其初始值是三個空串列:active,completed,和other。在每次迭代中,從當前狀態中獲取對應的串列,other作為回退,將當前元素推送給它。 - 使用
Map#values,得到三個串列 - 使用
Array#flat,回傳一個統一的串列,其中active首先顯示,然后是completed,然后是other。
const taskToShows = [ {task: "task2", status: "other status"}, {task: "task7", status: "active"}, {task: "task5", status: "active"}, {task: "task8", status: "completed"}, {task: "task1", status: "pending"}, {task: "task3", status: "progress"}, {task: "task4", status: "completed"}, {task: "task6", status: "active"} ];
const res = [...
taskToShows.reduce((lists, e) => {
const list = lists.get(e.status) ?? lists.get('other');
list.push(e);
return lists;
}, new Map([ ['active', []], ['completed', []], ['other', []] ]))
.values()
].flat();
console.log(res);
uj5u.com熱心網友回復:
當然你可以使用 sort():
const taskToShows = [{task: "task7", status: "completed"},{task: "task6", status: "active"},{task: "task5", status: "active"},{task: "task8", status: "completed"},{task: "task4", status: "completed"},{task: "task1", status: "pending"},{task: "task2", status: "other status"},{task: "task3", status: "progress"},{task: "task33", status: "active"},{task: "task77", status: "completed"}];
const statusOrder = {active: 0, completed: 1};
const result = taskToShows.sort(
({status: s1}, {status: s2}) => (statusOrder[s1] ?? Infinity) - (statusOrder[s2] ?? Infinity)
);
console.log(taskToShows);
.as-console-wrapper{min-height: 100%!important; top: 0}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/395709.html
標籤:javascript 排序
