0

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>';
               }
2

3 Answers 3

1

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>';
}
Sign up to request clarification or add additional context in comments.

2 Comments

Does sort work on array-type elements like that without a comparator function?
@Thilo: yes, because the default comparator is x.toString() <> y.toString() and toString is well defined for arrays.
0

?I want to sort it by lastname not firstname. The list should be displayed firstname followed by lastname.

fullnamearray.sort( function(a,b){
  var lastNameA = a.split(" ")[1];
  var lastNameB = b.split(" ")[1];
  return lastNameA.localeCompare( lastNameB );
})

Now you can display the list in the same manner you were doing earlier.

Above method will fail if firstname or lastname has a space character in between, so maybe you can follow what @Thilo has suggested

fullnamearray.push({first: firstname, last: lastName});
fullnamearray.sort( function(a,b){
  var lastNameA = a.lastName;
  var lastNameB = b.lastName;
  return lastNameA.localeCompare( lastNameB );
});

and display list as

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

Comments

0

Try this:

fullnamearray.push(firstname +" "+ lastname);
fullnamearray.sort(function (name1, name2) {
    return name1.split(' ')[1] > name1.split(' ')[1];
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.