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
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.