![](/img/trans.png)
[英]Javascript - How to compare and sort one array based on the order of second array?
[英]Sort array based on order value within second array
我有两个 Arrays:
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] ]
}
]
我想根据 dropdownOptions 数组中的sortOrder
值对侧边栏变量进行排序。 因此,对于此示例,预期的 output 将是:
const sortedSidebar = [
{
text: 'NuxtJS',
collapsible: true,
items: [ [Object], [Object], [Object], [Object] ]
},
{
text: 'VueJS',
collapsible: true,
items: [ [Object], [Object], [Object], [Object], [Object] ]
}
]
您可以首先将您的dropdownOptions
转换为Map ,它将每个text
/项目与订单相关联,以便快速轻松地查找。 下面我通过在dropdownOptions
上使用.map()
创建Map
来完成此操作,但是如果您可以更改dropdownOptions
数据结构,那么您可以避免此步骤并直接构建 Map。 拥有 Map 后,您可以对订单的差异使用.sort()
,根据 Map 中的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);
也许像...
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]; });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.