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
  • please post the content of fullnamearray array Commented May 12, 2016 at 5:12
  • Don't build the array like that, then. Maybe namearray.push({first: firstname, last: lastName}). Or push([firstname, lastname]). That way, you can sort it without splitting the string again (which may not even work for people like "Norma Jean Baker") Commented May 12, 2016 at 5:15

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.