Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

241
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!