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

243
Vistas
Cannot order array by multiple properties

I have this string Mario:Rossi;Giuseppe:Bianchi;Roberta:Rossi;Alessia:Verdi;Federico:Bianchi;Cristina:Verdi;Andrea:Rossi

I need to order it by last name, if is equal by first name, this is the expected output:

[“BIANCHI FEDERICO”, “BIANCHI GIUSEPPE”, “ROSSI ANDREA”, “ROSSI MARIO”, “ROSSI ROBERTA”, “VERDI ALESSIA”, “VERDI CRISTINA”];

what I did:

let input = "Mario:Rossi;Giuseppe:Bianchi;Roberta:Rossi;Alessia:Verdi;Federico:Bianchi;Cristina:Verdi;Andrea:Rossi";

let inputArr = input.split(';');

inputArr = inputArr.map(function(v, i, a) {
  let fullName = v.split(":");
  return {
    firstName: fullName[0],
    lastName: fullName[1]
  };
});

function orderByProp(inputArr, prop) {
  return inputArr.sort(function(a, b) {
    var nameA = a[prop].toLowerCase(),
      nameB = b[prop].toLowerCase();
    if (nameA < nameB)
      return -1;
    if (nameA > nameB)
      return 1;
    if (nameA === nameB)
      return -1
    return 0;
  });
}

let inputArrOrdered = orderByProp(inputArr, 'firstName');
inputArrOrdered = orderByProp(inputArr, 'lastName');


console.log(inputArrOrdered);

but the result is incorrect if the last name is equal

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

0

Sort, will sort by default in alphabetical order. So you just need a couple split and a sort.

let input = "Mario:Rossi;Giuseppe:Bianchi;Roberta:Rossi;Alessia:Verdi;Federico:Bianchi;Cristina:Verdi;Andrea:Rossi";


const sortedCapitalized = input
  .split(';') // split the different names
  .map(name => name
    .split(':') // split the name to first/last
    .reverse() // reverse so it becomes last/first
    .join(' ') // join to create a full name string
    .toUpperCase())
  .sort();

console.log(sortedCapitalized);


Now if the issue is just with the wrong result you get, that is because you return -1 when the values are equal. If you remove that part completely, it should work as expected.

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