Javascript sort a string array by last name

  • A+
Category:Languages

I have an array:

arr4=["John Alpha","Allen Beta", "Elle Cappa"]; 

I have a sort function that sorts a string array into descending order

function getSize(arr){ return arr.length; }  function sortStringArrDes(arr){ arrSize=getSize(arr); var temp; for(j=0; j<arrSize-1; j++){     for(i=0; i<arrSize-1; i++){         if (arr[i] < arr[i+1]){             temp = arr[i+1];             arr[i+1] = arr[i];             arr[i] = temp;             }         }     }     return arr; } 

Can I sort the array by surname using the sortStringArrDes or is there another, less complex way to do this?

 


Here I use .split(' ')[1] to get the lastname for the condition and it looks like it would work.

arr4=["John Alpha","Allen Beta", "Elle Cappa"];  function sortStringArrDes(arr){ arrSize=arr.length; var temp; for(j=0; j<arrSize-1; j++){     for(i=0; i<arrSize-1; i++){         if (arr[i].split(' ')[1] < arr[i+1].split(' ')[1]){             temp = arr[i+1];             arr[i+1] = arr[i];             arr[i] = temp;             }         }     }     return arr; }  console.log(sortStringArrDes(arr4))

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: