Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

157
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda