A guide on arranging and styling last names in an array in alphabetical order using JavaScript!

I created an array called moonwalkers and developed a function named alphabetizer to organize the names in alphabetical order with the last name appearing first.

Although it functions correctly, I am seeking ways to enhance the code.

For my reference, I used an interesting article from Hubrik and consulted Stack Overflow in order to understand how sorting works in JavaScript.

While attempting to modify the compare function and transform it into the last name variable, I encountered some difficulties. It seems that my struggle stems from the complexities of scopes and hoisting.

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));

Answer №1

The previous method of sorting names based on last names only is not recommended as it may not accurately sort individuals with the same last name according to their first names.

Consider using this alternative approach:

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));


Update: The revised version now includes the middle or nicknames in the sorting process. Keep in mind that it may not work as intended if the name contains suffixes like "Jr" or "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));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Passing an array of ID's between two components in Angular: A comprehensive guide

Greetings fellow readers, I have encountered a new challenge in my Angular project. I need to pass an array of IDs from one component to a completely unrelated component. Most solutions suggest using ViewChild, Input, or Output, but since the components ar ...

"Step-by-step guide on showcasing a specific blog post using its unique identifier in an Angular/Express/MongoDB application

I'm struggling to figure out how to retrieve a single blog post by its ID, especially since I am new to this. Currently, my main blog application has an ng-repeat functionality that fetches all posts. What I really want is the ability to click on a p ...

Tips for handling daily JavaScript tasks using Angular JS

Over the past few days, I've been diving into AngularJS. While it seemed intuitive in tutorials and videos, when I actually started replacing my current web app code with AngularJS, I encountered numerous issues. For instance, if I wanted to add HTML ...

Tips on displaying data in pie chart legend using react-chartjs-2

I am currently using a pie chart from react-Chartjs-2 for my dashboard. The requirement is to display both the label and data in the legend. I have implemented the following component in my application: import React, { Component } from "react"; ...

What could be causing my canvas to not display my sprite?

Currently, I am in the process of learning JavaScript and experimenting with creating games to make the learning experience more enjoyable. However, I am facing an issue while using EaselJS and CreateJS to develop these games as a beginner. I need some as ...

Develop a monitor for an entity that has not been created

Currently, I am tackling a feature that involves tracking an asynchronous request within a synchronous one. Let me elaborate. The code snippet I am working with looks something like this: const myObj = {}; function sendMessage(requestId, data) { kafkaP ...

What are the fundamental steps for setting up AJAX with a mongoDB server?

I need help with making an AJAX request to pull data from my database. I am looking for a simple example to check if a user exists before creating a new one. Currently, I am using mlabs and trying to understand how to access it through JavaScript. This p ...

Making a chain of multiple AJAX requests using jQuery

My current challenge involves retrieving data from select options on a website using JavaScript. Specifically, I am trying to obtain a list of zones within my country from a website that has this information. The issue I am facing is the hierarchical disp ...

Leveraging Angular 2 and RxJs 5 beta observables to continuously stream data from a while loop

I am looking to develop a straightforward Angular 2 application that calculates prime numbers within a while loop and continuously updates the view with newly discovered values. My goal is to showcase the list of prime numbers using *ngFor in real-time, gi ...

Determine the position of the cursor in an editable span

Is there a way to add text at the cursor position in an editable span when a button is clicked? The span contains multiple lines of text and HTML tags. [Take a look at this example on JSFiddle](http://jsfiddle.net/8txz9sjs/) ...

I am facing difficulties accessing an element within a controller in Angular

Struggling to access an element inside an AngularJS controller, I attempted the following: var imageInput = document.getElementById("myImage"); Unfortunately, this approach was unsuccessful as the element returned null. Curiously, when placing the statem ...

Error in Visual Studio with Angular 2 build: 'Promise' name not found

I recently started exploring Angular2 and followed the instructions provided in this quickstart guide: https://angular.io/guide/quickstart Everything seems to be working well after running npm install, but now I want to work on it within Visual Studio usi ...

Retrieve the text input from its respective radio button

There are two radio buttons, each accompanied by an input text field. When a user selects a radio button, they can also enter some corresponding text. My inquiry is: What is the best method to retrieve the entered text for the selected radio button? ...

Developing a JSON structure from a series of lists

var data = [ [ "default_PROJECT", "Allow", "Connect", "Allow", "AddComment", "Allow", "Write", "Allow", "ViewComments", "Allow", "ExportData", "Allow", ...

Creating an ArrayList of Integers in Java: A Step-by-Step Guide

I encountered an issue while trying to create an array of ArrayLists in my code. Here is what I attempted: ArrayList<Integer>[]list=new ArrayList<Integer>[128]; However, Eclipse displayed the following error message: Cannot create a generi ...

Display or conceal the location where the click event occurs within a single div

progress $(".button-toggle").click(function(e){ $(this).parents.find('#second').toggle(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="first"> <a href="#" class= ...

The use of "Undefined in res.redirect" is a common issue that may arise when working with a combination of libraries such as

Encountering an issue while trying to redirect the user to a signature route with the file name as a URL argument, and receiving undefined... Example of a file as a URL argument after upload: http://localhost:3000/undefined?arquivo-assinado=82a35943-5796 ...

Using the map function twice in React Native causes a rendering issue

<View style={styles.card} > {store.crud.list.map(function(element, index){ return ( <View style={styles.wrapper}> {element.map(function(number, index){ return( ...

Create a function that binds a select dropdown to each table column header using JavaScript Object Notation (JSON), and then populate an HTML table with the

I have a dynamic table populated with JSON data, and I would like to add a select dropdown for each column. The challenge is that the number of columns is not fixed and they are also populated by JSON. Therefore, I want the select dropdown at the top of ea ...

Unable to display material-ui icon when using a conditional ternary statement in React

I'm facing an issue where my app crashes when attempting to display a mui icon based on a certain condition. I suspect the problem lies in how I am using PriceCheckIcon within {}. Can someone provide assistance? <span style={ ...