我有一個物件陣列,我想根據它們是否包含一個字串來進行排序。
然后我想將那些與字串相匹配的物件按時間順序進行排序,然后將其余的物件按時間順序進行排序。
因此,
const role=waiter
const jobs=[
{
"date"/span>: "2021-09-30T00:00:00",
"角色": [廚師,搬運工]
},
{
"date": "2021-09-28T00:00:00",
"角色": [服務員, 廚師]
},
{
"date": "2021-09-29T00:00:00",
"角色": [服務員, 廚師]
},
{
"date": "2021-09-01T00:00:00",
"角色": [廚師]
},
]
應該變成:
[
{
"date"。"2021-09-28T00:00:00",
"角色": [服務員, 廚師]
},
{
"date": "2021-09-29T00:00:00",
"角色": [服務員, 廚師]
},
{
"date": "2021-09-01T00:00:00",
"角色": [廚師]
},
{
"date": "2021-09-30T00:00:00",
"角色": [廚師,搬運工]
},
]
到目前為止,我唯一能找到的解決方案是將陣列分成兩個獨立的陣列。對它們進行單獨排序,然后再將它們合并成一個。
我目前的解決方案是:
我目前的解決方案是:
我目前的解決方案是:
我目前的解決方案是
我目前的解決方案是:
const arrOne = jobs
.filter((j) => j.role.includes(role)
.sort((a, b) =>/span>
compareDesc(
a.date,b.date)
)
);
const arrTwo = jobs
.filter((j) => !j.role.includes(role) )
.sort((a, b) =>/span>
compareDesc(
a.date,b.date)
)
);
const finalArr = [...arrOne,...arrTwo] 。
是否有一個更優雅的解決方案?
最好是一個不需要將陣列分割成單獨的陣列的解決方案?
uj5u.com熱心網友回復:
你可以直接使用.sort,并輸入排序條件(如果兩個角色都匹配,則按日期排序,如果只有第一個,則優先,只有第二個,則優先,如果沒有,則按日期排序):
const chef = 'chef'/span>;
const porter = 'porter';
const waiter = 'waiter';
const role = waiter;
const jobs = [
{
"date": "2021-09-30T00:00:00",
"角色": [廚師,搬運工]
},
{
"date": "2021-09-28T00:00:00",
"角色": [服務員, 廚師]
},
{
"date": "2021-09-29T00:00:00",
"角色": [服務員, 廚師]
},
{
"date": "2021-09-01T00:00:00",
"角色": [廚師]
}
]
console.log(jobs.sort((a, b) => /span> {
if (a.role.includes(role) & & b. role.includes(role)) {
return new Date(a. date) - new Date(b.date) 。
} else if (a.role.includes(role) ) {
return -1;
} else if (b.role.includes(role) >) {
return 1;
}
return new Date(a. date) - new Date(b.date) 。
});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
這樣應該可以了。首先過濾,然后拼接。把找到的成員推到前面
const role = 'waiter'
const jobs = [
{
"date": "2021-09-30T00:00:00",
"role": ['chef', 'porter']
},
{
"date": "2021-09-28T00:00:00",
"role": ['waiter', 'chef']
},
{
"date": "2021-09-29T00:00:00",
"role": ['waiter', 'chef']
},
{
"date": "2021-09-01T00:00:00",
"角色": ['chef']
},
]
const jobFound = jobs.some(job => job。 role.includes(role)); //過濾匹配的角色。
if (jobFound) {
const sortedJobs = jobs.filter((job) => job。 role.includes(role)); //filter desired data.
sortedJobs.sort((a, b) => a.date. localeCompare(b.date)); //按日期排序。
sortedJobs.forEach((job) => jobs.splice(jobs. indexOf(job), 1)); //拼接被匹配的物件。
jobs.sort((a, b) => a.date. localeCompare(b.date)); //為我們的原始陣列排序。
jobs.unshift(...sortedJobs); //將有序的成員推到陣列的前面。
}
console.log(jobs)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/310832.html
標籤:
