Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

242
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda