Bonteq
Bonteq

Reputation: 871

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

Upvotes: 0

Views: 37

Answers (2)

Hafthor
Hafthor

Reputation: 16896

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

Upvotes: 1

Nick Parsons
Nick Parsons

Reputation: 50664

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

Upvotes: 1

Related Questions