1

I recently started learning JavaScript, and I am stuck on a problem. I tried searching previous questions, and I did not find a similar question. The prompt is asking me to reorder the list by last name, first name in alphabetical order.

My issue deals with the last item in the array. Since a comma is not needed for the last item, the output on console.log results in the last name in the array not having a comma separating the last name and first name.

I am thinking the solution is putting an if statement in between nameQueue.reverse and nameQueue.join. I tried looking up the correct RegExp to use to look for a comma and return true or false, but it was little over my head.

Does anyone see a easy solution for this?

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) {
    // Your code goes here!
    var list = names.join(", ");
    list = list.split(" ");
    var reorderName = [];
    for (i=0; i < names.length; i++){
        var nameQueue = list.splice(0,2);
        nameQueue = nameQueue.reverse();
        nameQueue = nameQueue.join(" ");
        reorderName = reorderName.concat(nameQueue);
        reorderName.sort();
    }
        return reorderName;

}

// Try logging your results to test your code!
console.log(alphabetizer(moonWalkers));
1
  • 2
    This is a really weird solution to this problem. You shouldn't be joining the entire list together, and then breaking it apart. What if what of the names was "Vincent van Gogh"? You should leave the array of names alone, with each name as a separate element, then individually reverse the names. Once that is done, you can simply sort the array. At no point should you concatenate the entire list of names prior to actually wanting to output it.
    – user229044
    Dec 27, 2014 at 22:14

5 Answers 5

1

I won't attempt to salvage your solution and inject the missing ,, because that's really not how you should solve this. That is a dead-end solution, it's overly complex and works on an extremely limited subset of inputs. It will need to be completely scrapped and rewritten almost immediately in any real-world scenario, as joining an array array of 100,000 names to produce a string only to immediately break it by a new delimiter is going to be pretty untenable, since you already have the array you need to sort.

The correct way to solve this is to leave the array intact, and mutate the individual elements. Then, sort the entire list:

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

// For each element, split it, reverse it, join it,
// producing [ 'Armstrong, Neil', 'Aldrin, Buzz', etc ]
names = names.map(function (n) { return n.split(' ').reverse().join(', ') });

// Simply sort the resulting array, and you're done
console.log(names.sort());

My solution will likely also fail when a new name such as "Vincent van Gogh" is introduced. The difference is that my solution is one line of code, which can easily be modified to accommodate specific rules for names, or thrown out and rewritten without a second thought. The underlying algorithm of mutating array into a state where it can simply be sorted will always be retained by whatever solution replaces mine; the key is that I'm not writing a sorting algorithm, I'm just writing the part that knows how to mutate names.

3
  • @meager I like these solutions, they are very clean. Also hocus pocus for beginning programmers. I've been reading up with those modern array functions. It seems that for and while lus are sometimes quicker than using functions like map. jsperf.com/map-vs-native-for-loop/7. For this example it won't really matter of course.
    – Mouser
    Dec 27, 2014 at 22:29
  • I will look at the documentation to get a better understand of the map method to see how that is working. I appreciate the solution. Since it is not ideal for me to change the console.log (given in the question), I ended up adding another return name.sort to the end. Dec 27, 2014 at 22:30
  • 1
    If speed is actually a concern, you'll find bottlenecks after you have a working solution. Don't avoid things like map or forEach because you read somewhere that they're slow. Chances are very good that you will never know the difference. Until you actually demonstrate a need to optimize, write your code for readability and maintainability.
    – user229044
    Dec 27, 2014 at 22:30
0

An easy but not clean way to do it is to add ',' to the last element of the array before reordering.

0

What you're basically doing is appending a comma to each string, with the join / split. I would add a "custom" comma to the end of the string, right here:

var list = names.join(", ");
list += ",";
list = list.split(" ");

Also, I'd avoid using the same variable to hold different data types (list). Even if Javascript is flexible and allows yo to do that, it's not pretty and leads to confusion.

0

An other approach to your problem. I split the string upon the last space. Then rearrange the values and put them back into the copied array. Finally let sort do it's work. This navigates around the Vincent van Gogh problem.

var reorderName = moonWalkers.slice(0); //copy the array

for (var i=0; i < reorderName.length; ++i){
    var lastName = reorderName[i].substr(reorderName[i].lastIndexOf(" "));
    var name = reorderName[i].substr(0, reorderName[i].lastIndexOf(" "));

    //output is: Gogh, Vincent van
    var fullName = lastName + ", " + name; //append that comma!
    reorderName[i] = fullName;

    reorderName.sort();
}

return reorderName;
2
  • Thanks! I could actually follow along with this. Is there a difference between using substr and slice to get the answer? They seem pretty similar. I would vote up if I had the reps. Dec 27, 2014 at 22:56
  • array.slice copies array elements without changing the array. String.slice and String.substr more or less do the same thing in most cases. Except that slice takes up to two indexes as arguments (Can also be negative) and substr takes an index for as first argument and the length of the string as a second optional. Consider this string: hello. "hello".substr(-2, 2) would print lo, while "hello".slice(-2, 2) would result in an empty string.
    – Mouser
    Dec 27, 2014 at 23:06
0

Another way you can do this is by just writing a custom sort function that compares against the last word. This presumes that the last word is the surname, which is a big assumption to make, but it doesn't mutate the original array elements. (Your question doesn't make it clear that it's necessary to convert FORENAME LASTNAME into LASTNAME, FORENAME, just that you want the array sorted by last name).

var getLastWord = (function() {
  var lastWord = /\w+$/;

  // Return a function which returns the last word in a string
  return function(str) {
    return lastWord.exec(str)[0];
  };
})();

// Comparison function by last word in string
var compareByLastWord = function(a, b) {
  return getLastWord(a) > getLastWord(b);
};

moonWalkers.sort(compareByLastWord);
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.