JessieBear JessieBear - 6 months ago 10
Javascript Question

Sort array with multiple values in Javascript

How do you sort an array like this

fullnamearray.push(firstname +" "+ lastname);
?I want to sort it by lastname not firstname. The list should be displayed firstname followed by lastname.

code

fullnamearray.push(firstname +" "+ lastname);
fullnamearray.sort();
for(var i = 0; i < fullnamearray.length; i++){
Name.innerHTML += '<li>' + fullnamearray[i] + '</li>';
}

Answer

Concatenate them when you output, not when you store:

fullnamearray.push([lastname, firstname]);
fullnamearray.sort();
for(var i = 0; i < fullnamearray.length; i++){
     Name.innerHTML += '<li>' + fullnamearray[i][1] + " " +  fullnamearray[i][0] + '</li>';
}
Comments