skip to Main Content

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


  1. 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'

    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' ];
    
    console.log(people.sort());
    Login or Signup to reply.
  2. The variables are simply mislabelled, see the following:

    const alpha = people.sort((a, b) => {
        const [aLast, aFirst] = a.split(', '); // expected and got ["Bernhard", "Sandra"]
        const [bLast, bFirst] = b.split(', '); // expected and got ["Bethea", "Erin"]
        return aLast > bLast ? 1 : -1;
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search