I want to Sort the people alphabetically by last name. I’m curious if there’s a more professional approach to doing that.
My Array :
const people = [ 'Bernhard, Sandra', 'Bethea, Erin', 'Becker, Carl', 'Bentsen, Lloyd', 'Beckett, Samuel', 'Blake, William', 'Berger, Ric', 'Beddoes, Mick', 'Beethoven, Ludwig', 'Belloc, Hilaire', 'Begin, Menachem', 'Bellow, Saul', 'Benchley, Robert', 'Blair, Robert', 'Benenson, Peter' ];
The code is working properly, but I am confused about why the split method returns inverse values.
Despite asking Poe for help, I am still confused.
The positions of the destructured variables were swapped by Poe when I asked for help but I haven’t changed the code yet.
const alpha = people.sort((a, b) => {
const [aFirst, aLast] = a.split(', '); // expected ["Bernhard", "Sandra"] Not [ 'Sandra', 'Bernhard' ]
const [bFirst, bLast] = b.split(', '); // expected ["Bethea", "Erin"] Not [ 'Erin', 'Bethea' ]
return aFirst > bFirst ? 1 : -1;
})
console.table(alpha);
2
Answers
Your array already contains strings of names where the last name is the first part of the string, so you can just call the
.sort()
method.Oh, and your array contains a typo:
'Blake, 'William'
should be:'Blake, William'
The variables are simply mislabelled, see the following: