我的任務是接收一組代表“顧問”的物件,每個物件都有 ID,并根據會話預訂的最新選定顧問重新排列它們。
所以我有一系列即將到來的會話物件,其中最近到最后:

我有一系列所有顧問的物件:

所以'顧問'therapistId的'upcomingSessions'比賽id
我撰寫了一個方法,將治療師從“upcomingSessions”拉到一個新陣列中,然后連接剩余的,保持“upcomingSessions”治療師的順序。
因此,用戶將從下拉選單中看到最近選擇的治療師。
我寫的方法有效,但它有一個嵌套forEach()回圈,因為filter()只選擇了使用過的顧問,但不保持順序。
這是方法:
const handleUpdatedConsultantList = () => {
// first capture the ids of chosen therapists
const consultantIds = upcomingSessions.map((us) => us.therapistId)
// create an array of remaining therapists
const remainingConsultants = consultants.filter(
(c) => !consultantIds.includes(c.id),
)
// empty array to push in the entire object of each chosen therapist
const recentConsultants: ConsultantType[] = []
// method to push in therapists by most recent
consultantIds.forEach((c) => {
consultants.forEach((co) => {
if (c === co.id) {
recentConsultants.push(co)
}
})
})
// concat most recent with remaining
return recentConsultants.concat(remainingConsultants)
}
我的問題是,這是實作這一點的最佳方式嗎?嵌套回圈總是讓我感到不安,但也許這是保持選定顧問順序的唯一方法?
這將獲取過濾后的選定顧問,但將 id 從最小到最大排序,而不是選擇的順序:
const selectedConsultants = consultants.filter((c) => [313, 312, 311, 302].includes(c.id))
uj5u.com熱心網友回復:
地圖可以很好地完成這項作業:
const upcomingSessions = [
{therapistId: 5},
{therapistId: 8},
{therapistId: 9},
{therapistId: 7}
];
const consultants = [
{id: 1},
{id: 2},
{id: 3},
{id: 5},
{id: 6},
{id: 7},
{id: 8},
{id: 9},
{id: 10},
{id: 11},
{id: 12}
];
const recentConsultants = new Map(upcomingSessions.map(us => [us.therapistId, ]));
consultants.forEach(c => recentConsultants.set(c.id, c));
console.log([...recentConsultants.values()]);
uj5u.com熱心網友回復:
我認為您可以recentConsultants在find()映射到consultantIds.
const handleUpdatedConsultantList = () => {
// first capture the ids of chosen therapists
const recentConsultantIds = upcomingSessions.map((us) => us.therapistId);
// map through ids and connect with consultant profiles
const recentConsultants = recentConsultantIds.map((id) =>
consultants.find((c) => c.id === id)
);
// create an array of remaining therapists
const remainingConsultants = consultants.filter(
(c) => !recentConsultantIds.includes(c.id)
);
// concat most recent with remaining
return recentConsultants.concat(remainingConsultants);
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/454052.html
標籤:javascript 排序 过滤 嵌套循环
下一篇:Prolog問題{串列}
