Home > database >  Sort array based on order value within second array
Sort array based on order value within second array

Time:08-07

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

CodePudding user response:

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

CodePudding user response:

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