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

170
Vistas
Sort array object based on another array in javascript

How can i sort and rearrange an array that looks like this

fields = [
  {
    uid: '2c2162cc-37d0-f1e3-96c2-6d9ccb50f38d',
    field: new ObjectId("627f816d8443318c6aaa1220"
  },
  {
    uid: '2aa60f96-135b-e179-2b46-516c87a877cc',
    field: new ObjectId("6283cb3ca573a56e11587c46"),
  }
]

to match the arrangement of this array:

order = [ '6283cb3ca573a56e11587c46', '627f816d8443318c6aaa1220' ]

Here is the output I’m looking for:

[
{
    uid: '2aa60f96-135b-e179-2b46-516c87a877cc',
    field: new ObjectId("6283cb3ca573a56e11587c46"),
  },
  {
    uid: '2c2162cc-37d0-f1e3-96c2-6d9ccb50f38d',
    field: new ObjectId("627f816d8443318c6aaa1220"),
  }
]

findIndex and sort but I am very confused

fields.sort((a: any, b: any) => order.indexOf(a.field) - order.indexOf(b.field)) // It does not work
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You need to use sort method on the array. And then compare the index of field on the order array.

const data = [
{
    uid: '2aa60f96-135b-e179-2b46-516c87a877cc',
    field: "6283cb3ca573a56e11587c46",
    value: 'test val 6'
  },
  {
    uid: '2c2162cc-37d0-f1e3-96c2-6d9ccb50f38d',
    field: "627f816d8443318c6aaa1220",
    value: ''
  }
]

const order = [ '6283cb3ca573a56e11587c46', '627f816d8443318c6aaa1220' ];

data.sort((a,b) => order.indexOf(a.field) - order.indexOf(b.field));
console.log(data);

Notice: ObjectId class is not defined here, so I changed it to string here for simplicity.

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