What is the most effective way to alphabetically organize a Javascript array?

Is there a more professional way to sort people alphabetically by last name in an array?

Here is the array I'm working with:

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' ];

Although my code is functioning correctly, I'm puzzled by the unexpected results of the split method. Even after seeking help from Poe, I am still unsure.

When Poe assisted me, the positions of the destructured variables were changed, but I have not yet modified the code.

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

Answer №1

You've got a good start with your array of names already in the correct format, so all you need to do is use the .sort() method on it.

By the way, there is a small typo in your array:

'Blake, 'William' should actually 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());

Answer №2

This code snippet seems to have a mislabeled variables, as shown below:

const alpha = people.sort((a, b) => {
    const [aLast, aFirst] = a.split(', '); // expected values: ["Bernhard", "Sandra"], but got ["Bethea", "Erin"]
    const [bLast, bFirst] = b.split(', '); // expected values: ["Bethea", "Erin"], but got ["Bernhard", "Sandra"]
    return aLast > bLast ? 1 : -1;
})

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

What is the best way to customize the behavior of multiple instances of ng-include within the same view?

My goal is to have unique behavior for each instance of the calendar that I include multiple times in my main HTML view. Specifically, I want to display 3 different dates based on the day selected in each calendar. In my main HTML view, I have included th ...

Filling form fields with data from a dynamically created table using jQuery

I am facing an issue with populating the fields in the input box of my modal. The modal appears after clicking the Edit button in a table, and it should populate the fields based on the table row where the button is clicked. The table is generated using jQ ...

using document references in puppeteer's evaluate/waitFor function

I'm feeling a bit lost when it comes to understanding the document reference in puppeteer's evaluate method. The official documentation shows some code that includes this reference within a waitFor function in a node script. I get that these line ...

What is the solution for resolving the JavaScript error "TypeError: Cannot read property 'map' of undefined"?

I'm encountering an issue while fetching data from the API and trying to map it to display in a table. The problem is that the fetching process doesn't seem to be working properly, resulting in the state remaining undefined when the page loads. I ...

Are there any techniques for running unit tests on a Vue.js transition?

I have been working on a Vue component that includes a transition with a dynamically generated name. My challenge is to test whether the transition name is correctly set based on the props I pass into the component. Below is the code snippet of the compone ...

Material UI select field box not displaying the chosen option

After implementing a select component with Mui, I encountered an issue where although the selected option gets stored correctly in the defined state, it does not display within the select box itself. Below is the JSON object used: const DataExample = [ { ...

Utilizing babel-plugin-root-import in conjunction with babel 7

Recently, I decided to dive into setting up Babel 7 for the first time. It's been a bit of a learning curve as I navigate through unfamiliar territory. While I was able to successfully install and utilize @babel/plugin-proposal-optional-chaining, I&ap ...

Streamline the process of renaming or remapping keys in a collection of JavaScript/JSON objects

Structured JSON data is essential. Imagine using JSON.parse(): [ { "title": "pineapple", "uid": "ab982d34c98f" }, { "title": "carrots", "uid": "6f12e6ba45ec" } ] The goal is to transform it by changing titl ...

What are the steps to ensure my MERN application refreshes properly when deployed on Heroku?

After successfully deploying my MERN app to Heroku, I encountered an issue where pages would come up blank when refreshed. Despite being able to navigate between pages using the nav bar without any errors, a page refresh renders them empty. This troublin ...

Refresh Browser with Angular UI State Parameters

I'm seeking assistance on an issue I've encountered while using angularjs 1.5.5 and angular-ui-router 0.4.2. Specifically, when refreshing the browser, I face a problem that seems to be implementation-specific. Below is a sample code snippet of ...

How do you structure `en.js` or `ja.js` files for lazy loading in vue-i18n?

What is the correct format for lazy loading en.js or ja.js? The code below is not working: // en.js export default { title: 'Title', greeting: 'How are you' }; and import Vue from 'vue'; import Inven ...

What is the process for making an XHR request to a server located remotely

Do you think the code below is sufficient for XHRing a remote server? I tried putting the full server URL in the open method of the XHR object, but it didn't work. I'm not sure if something else needs to be added. <script type="text/javascrip ...

Steps to retrieve a value from a promise function

My current challenge involves a function that verifies whether a device is online. Take a look at the code snippet below. const ping = require('ping'); export function checkDeviceStatus(device) { try { const hosts = [device]; let resul ...

Adjust the div class to align with its content

I am looking to modify the code in order to copy the text of a div to its own class. Currently, the code provided copies text from all sibling div elements, but I specifically want each individual div's text to be its own class. For example, with the ...

The Datejs library is experiencing issues following an upgrade to jQuery 3.x

I'm currently working on a node.js project that utilizes the Datejs library. However, after updating our local jQuery file from version 1.9.1 to 3.6.0, this library has stopped functioning properly. Here is a snippet of the code: var today = Date ...

What steps should I take to implement asynchronous functionality in my code for a Google Chrome Extension?

I am currently working on a Google Chrome extension that needs to gather data from two different servers and send it to another service. I am facing an issue with making the process asynchronous, even though the requests are functioning properly. After se ...

AngularJS: dependent dropdown menus

Attempting to create a cascade dropdown in Angular, I assumed it would work seamlessly with binding. Here is the code snippet: <select name="client" ng-model="selectedRequest.client" ng-options="c.name for c in clients track by c.id" req ...

Customize your JQuery/HTML5 Slider to accept user input

Currently, I am developing a time tracking mobile application in MVC4, which includes the use of a slider input type. <input type="range" name="time_verdi" id="slider" value="7.5" min="0.0" max="24" step="0.5" data-highlight="true"/> When using thi ...

Retrieve the customized attribute from the chosen option within the datalist

Is there a way to retrieve the custom attribute "location" of an option selected from a datalist and display it? I understand that for a select element we can use selectedIndex, but how can this be achieved with datalist? <!DOCTYPE html> <html&g ...

Complicated "as-label" for understanding expressions in Angular

Is it possible to set a complex label in a comprehension expression in Angular? I've searched everywhere for a solution, but I can't seem to find one. The workaround I found involves pre-populating the 'as' label attribute with the des ...