代码之家  ›  专栏  ›  技术社区  ›  Bonteq

根据第二个数组中的顺序值对数组进行排序

  •  0
  • Bonteq  · 技术社区  · 2 年前

    我有两个数组:

    const dropdownOptions = [
      { text: 'NuxtJS', sortOrder: 1 },
      { text: 'VueJS', sortOrder: 2 },
    ]
    

    以及:

    const sidebar = [
      {
        text: 'VueJS',
        collapsible: true,
        items: [ [Object], [Object], [Object], [Object], [Object] ]
      },
      {
        text: 'NuxtJS',
        collapsible: true,
        items: [ [Object], [Object], [Object], [Object] ]
      }
    ]
    

    我想根据 sortOrder dropdownOptions数组中的值。因此,对于本例,预期输出为:

    const sortedSidebar = [
      {
        text: 'NuxtJS',
        collapsible: true,
        items: [ [Object], [Object], [Object], [Object] ]
      },
      {
        text: 'VueJS',
        collapsible: true,
        items: [ [Object], [Object], [Object], [Object], [Object] ]
      }
    ]
    
    2 回复  |  直到 2 年前
        1
  •  1
  •   Nick Parsons Felix Kling    2 年前

    您可以先转换 dropdownOptions 变成 Map 将每个 text /带有订单的项目,以便快速轻松地查找。下面我通过创建 Map 使用 .map() 在…上 下拉选项 ,但如果你能改变 下拉选项 数据结构,则可以避免此步骤,直接构建Map。一旦你有了地图,你就可以使用 .sort() 关于顺序的差异,根据 sortOrder 地图内持有的财产。

    参见下面的工作示例:

    const dropdownOptions = [ { text: 'NuxtJS', sortOrder: 1 }, { text: 'VueJS', sortOrder: 2 }, ];
    const sidebar = [ { text: 'VueJS', collapsible: true, items: [] }, { text: 'NuxtJS', collapsible: true, items: [] } ];
    
    const sortMap = new Map(dropdownOptions.map((obj) => [obj.text, obj.sortOrder]));
    const sortedSidebar = sidebar.slice().sort((a, b) => sortMap.get(a.text) - sortMap.get(b.text));
    console.log(sortedSidebar);
        2
  •  1
  •   Hafthor    2 年前

    也许是。。。

    const dropdownOptionsMap = dropdownOptions.reduce((a,v)=>{ a[v.text]=v; return a; },{});
    const sortedSidebar = sidebar.slice().sort((a,b) => { return dropdownOptionsMap[a.text].sortOrder - dropdownOptionsMap[b.text]; });