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

223
Vistas
How to sort double objects?

I have an array. The data in the array is in the following format.

var test = [
    {
    "a" : {
        "order" : 100,
    }
  },
  {
    "b" : {
        "order" : 10,
    }
  },
  {
    "c" : {
        "order" : 1,
    }
  },
];

I want to sort this data according to order value. Is there any way to do this?

about 4 years ago · Santiago Gelvez
2 Respuestas
Responde la pregunta

0

You can use JS custom sort from Array.prototype.sort(), reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Then you can sort by comparing the two element's order, but you still need to determine it's key/attribute (e.g.: a or b or c)

Here, you can use Object.keys() function and take the first key in the object, reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Here's a working example:

var test = [
    {
    "a" : {
        "order" : 100,
    }
  },
  {
    "b" : {
        "order" : 10,
    }
  },
  {
    "c" : {
        "order" : 1,
    }
  },
];



//console.log(test);


test.sort((firstEl, secondEl) => { 
    var key1 = Object.keys(firstEl)[0];
    var key2 = Object.keys(secondEl)[0];
    return firstEl[key1].order - secondEl[key2].order
} );
console.log(test);

Output:

[
  {
    "c": {
      "order": 1
    }
  },
  {
    "b": {
      "order": 10
    }
  },
  {
    "a": {
      "order": 100
    }
  }
]
about 4 years ago · Santiago Gelvez Denunciar

0

You can use Object.values to get the first property value and access the order property on that to compare.

let test=[{a:{order:100}},{b:{order:10}},{c:{order:1}}];
test.sort((a, b)=>Object.values(a)[0].order - Object.values(b)[0].order);
console.log(test);

For a more generalized solution, you can create a key extractor function to get the value to compare by.

let test=[{a:{order:100}},{b:{order:10}},{c:{order:1}}];
const getOrder = x => Object.values(x)[0].order;
test.sort((a, b)=>getOrder(a) - getOrder(b));
console.log(test);

about 4 years ago · Santiago Gelvez 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