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

123
Vistas
How can i sort array of objects based on numbers and spefific letters?

i have this array


let arr = [
    {
        "time": "3",
        "wholeObj": "abc mo sa 3 Y",
        "mapEventValue": "Y"
    },
    {
        "time": "3",
        "wholeObj": "abc a 3 G",
        "mapEventValue": "G"
    },
    {
        "time": "3",
        "wholeObj": "cba d 3 S f",
        "mapEventValue": "S"
    },
    {
        "time": "3",
        "wholeObj": "cba z 3 R",
        "mapEventValue": "R"
    }
]

i need to sort the array FIRST based on the time value and after that if the time values are equal i need to sort them based on mapEventValue in following order G Y R S

So in my case all objects are having equal time values 3 I can't find a way to sort them by the mapEventValue property

what i tried

Until now i just managed to sort them by time value

let sorted = arr.sort((a,b) => a.time - b.time)

So my output at the end should be


let arr = [
    {
        "time": "3",
        "wholeObj": "abc a 3 G",
        "mapEventValue": "G"
    },
    {
        "time": "3",
        "wholeObj": "abc mo sa 3 Y",
        "mapEventValue": "Y"
    },
    {
        "time": "3",
        "wholeObj": "cba z 3 R",
        "mapEventValue": "R"
    },
    {
        "time": "3",
        "wholeObj": "cba d 3 S f",
        "mapEventValue": "S"
    },
]
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

So only sort by time if time differs, otherwise sort by the index of your desired sort order.

let sortOrder = 'GYRS';
let arr = [
    {
        "time": "3",
        "wholeObj": "abc mo sa 3 Y",
        "mapEventValue": "Y"
    },
    {
        "time": "3",
        "wholeObj": "abc a 3 G",
        "mapEventValue": "G"
    },
    {
        "time": "3",
        "wholeObj": "cba d 3 S f",
        "mapEventValue": "S"
    },
    {
        "time": "3",
        "wholeObj": "cba z 3 R",
        "mapEventValue": "R"
    }
];

let sorted = arr.sort((a,b) => {
  if (a.time != b.time) {
    return a.time - b.time;
  } else {
    return sortOrder.indexOf(a.mapEventValue) - sortOrder.indexOf(b.mapEventValue);
  }
});
console.log(sorted);

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