How to sort and format names in an array alphabetically in JavaScript

I have an array moonwalkersand wrote a function alphabetizerto sort the names in alphabetical order and first format them with the last name.

It works great, but how do I write code better?

I used this article from a Hubrik article and referenced Stack Overflow to understand how sorting works in JS.

I tried to rework the function comparein a variable last nameand made a mess. I suspect this is because I'm still trying to raise my head around areas and climbs.

var moonWalkers = [
  "Neil Armstrong",
  "Buzz Aldrin",
  "Pete Conrad",
  "Alan Bean",
  "Alan Shepard",
  "Edgar Mitchell",
  "David Scott",
  "James Irwin",
  "John Young",
  "Charles Duke",
  "Eugene Cernan",
  "Harrison Schmitt"
];


var finalNameList = [];

function alphabetizer(names) {
    
    // compare last names
    function compare (a, b) {
        var aName = a.split(" ");
        var bName = b.split(" ");
        var aLastName = aName[aName.length - 1];
        var bLastName = bName[bName.length - 1];
        
        if (aLastName < bLastName) return -1;
        if (aLastName > bLastName) return 1;
        return 0;
    }
    
    names.sort(compare);
    
    // to format names
    for (i = 0; i < names.length; i++) {
        var lastName = names[i].split(" ")[1];
        var firstName = names[i].split(" ")[0];
        var newName = lastName + ", " + firstName;
        
        //  push newName to global var finalNameList
        finalNameList.push(newName);
    }
    
    return finalNameList;
}

console.log(alphabetizer(moonWalkers));
Run codeHide result
+4
source share
1

, . .

:

var moonWalkers = [
  "Neil Armstrong",
  "Buzz Aldrin",
  "Pete Conrad",
  "Alan Bean",
  "Alan Shepard",
  "Edgar Mitchell",
  "David Scott",
  "James Irwin",
  "John Young",
  "Charles Duke",
  "Eugene Cernan",
  "Harrison Schmitt"
];

function alphabetizer(names) {
    var list = [];

    // format names first
    for (i = 0; i < names.length; i++) {
        var lastName = names[i].split(" ")[1];
        var firstName = names[i].split(" ")[0];
        var newName = lastName + ", " + firstName;
        
        //  push newName to global var finalNameList
        list.push(newName);
    }

    // compare entire name
    return list.sort();
}

console.log(alphabetizer(moonWalkers));
Hide result

: . , , "Jr" "Esq".

var moonWalkers = [
  "Neil Armstrong",
  "Edwin \"Buzz\" Aldrin",
  "Charles \"Pete\" Conrad",
  "Alan Bean",
  "Alan Shepard",
  "Edgar Mitchell",
  "David Scott",
  "James Irwin",
  "John Young",
  "Charles Duke",
  "Eugene Cernan",
  "Harrison \"Jack\" Schmitt"
];

function alphabetizer(names) {
  return names.map(function(name) {
    var full = name.split(" "),
      last = full.pop();
    return last + ", " + full.join(" ");
  }).sort();
}

console.log(alphabetizer(moonWalkers));
Hide result
+1

Source: https://habr.com/ru/post/1651855/


All Articles