Re-ordering 一个 objects 数组基于 Javascript 中另一个数组的数据(React)

Re-ordering one array of objects based on data from another array in Javascript (React)

我的任务是接收一个 objects 数组,代表 'consultants',每个数组都有 ID,re-arranging 它们基于最近选择的 [=55] 顾问=]预订。

所以我有一个 objects 即将到来的 session 的数组,最近的到最后的:

我有一组 objects 所有顾问:

所以 'upcomingSessions' 的 therapistId 匹配 'consultants'

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

我的问题是,这是实现它的最佳方式吗?嵌套循环总是让我 un-easy 但也许这是保持所选顾问顺序的唯一方法?

这会获取过滤后的选定顾问,但会将 ID 从小到大排序,而不是按照选定的顺序排序:

const selectedConsultants = consultants.filter((c) => [313, 312, 311, 302].includes(c.id))

我认为在 consultantIds.

上映射时,您可以使用 find() 查找更直接地获取 recentConsultants 的列表
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);
};

A Map 可以很好地完成工作:

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