简体   繁体   中英

Sort array based on order value within second array

I have two Arrays:

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

And:

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

I'd like to sort the sidebar variable based on the sortOrder value within the dropdownOptions array. So, for this example, the expected output would be:

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

You can first convert your dropdownOptions into a Map that associates each text /item with an order for quick and easy lookup. Below I've done that by creating a Map using .map() on dropdownOptions , but if you can change the dropdownOptions data structure then you can avoid this step and build the Map directly. Once you have the Map, you can use .sort() on the difference of the orders to rearrange your array in ascending order based on the sortOrder property held within the Map.

See working example below:

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

maybe something like...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM