Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

156
Views
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] ]
  }
]
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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]; });
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!