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

106
Vistas
Sort Array with two object inside

i want to ask about array.sort() was looking for solution about this kind of problem how to sort a array with this kind of structure

  array.sort((a, b) => a.foo.foo1.foo2 - b.foo.foo1.foo2)

where this working but after rewrite the code for multiple use case

export const handleSort = (arr, sortBy, desc) => {
 arr = [...arr];

   if (desc) {
     return arr.sort((a, b) => b[sortBy] - a[sortBy]);
   } else {
     return arr.sort((a, b) => a[sortBy] - b[sortBy]);
   }

later on if i need like

  return arr.sort((a, b) => b[sortBy][0][1] - a[sortBy][0][1]);

i cant use this

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You could use a function and an array for getting the right property.

const
    getValue = (object, keys) => keys?.length
        ? keys.reduce((o, k) => o[k], object)
        : object,
    ASC = (a, b) => a - b,
    DESC = (a, b) => b - a,
    sortBy = (order, keys) => (a, b) => order(getValue(a, keys), getValue(b, keys)),
    keys = ['foo', 'foo1', 'foo2'],
    data = [{ foo: { foo1: { foo2: 7 } } }, { foo: { foo1: { foo2: 2 } } }, { foo: { foo1: { foo2: 9 } } }, { foo: { foo1: { foo2: 6 } } }, { foo: { foo1: { foo2: 1 } } }, { foo: { foo1: { foo2: 4 } } }];

// usage
data.sort(sortBy(ASC, keys)); 

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Denunciar

0

Maybe a good idea is to define function that will handle getting properties for the compare purpose?

const handleSort = (arr, desc, getValue) => {
  if (desc) {
    return arr.sort((a,b) => getValue(a) - getValue(b));
  } 

  return arr.sort((a,b) => getValue(b) - getValue(a));

}

In this way, you can use upper function like:

return handleSort(myArray, true, (obj) => obj.foo.foo1.foo2);
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