Order by surname in the alphabet

In what way can we organize the data from an array of objects alphabetically by last name when there is no separate property for first and last names, but rather a single property called fullname (see example data below)?

If we were to sort the data by last name, it would result in the following order based on the provided data.

One challenge that arises is dealing with names such as "James van der Wal," "Mary Tyler Moore," "Erik the Great," and "Madonna." How can this scenario be efficiently managed? Any assistance would be greatly appreciated. Thank you. I currently have a solution outlined below but am open to suggestions. Thank you.

Alexa Bermodes
Bryan Christian
Alen Geizer
Philipp Hym
Mattew Merrillos
Emil Ortizano
Ivana Turnerre
Steven Weinraucherche

#Object - names

[
    {
        "id": 2,
        "display": "Alen Geizer",
        "subDisplay": null,
        "attribute1": null,
        "attribute2": null
    },

    {
        "id": 9,
        "display": "Emil Ortizano",
        "subDisplay": null,
        "attribute1": null,
        "attribute2": null
    },
    {
        "id": 10,
        "display": "Philipp Hym",
        "subDisplay": null,
        "attribute1": null,
        "attribute2": null
    },
    {
        "id": 11,
        "display": "Bryan Christian",
        "subDisplay": null,
        "attribute1": null,
        "attribute2": null
    },
    {
        "id": 12,
        "display": "Ivana Turnerre",
        "subDisplay": null,
        "attribute1": null,
        "attribute2": null
    },
    {
        "id": 13,
        "display": "Mattew Merrillos",
        "subDisplay": null,
        "attribute1": null,
        "attribute2": null
    },
    
    {
        "id": 1,
        "display": "Alexa Bermudes",
        "subDisplay": null,
        "attribute1": null,
        "attribute2": null
    },
    {
        "id": 2299,
        "display": "Steven Weinraucherche",
        "subDisplay": null,
       "attribute1": null,
       "attribute2": null
   }
]

#code

#code

getSampleListOfNames() {
this.isLoading = true;
this._sample.getSampleListNames(id, '')
  .pipe(
    finalize(() => this.isLoading = false),
  ).subscribe({
    next: (res) => {
      if (res.data) {
       res.data.sort((a,b) => a.display.split(" ")[1] > b.display.split(" ")[1] ? 1: -1);
        this.names = res.data;
      }
    },
    error: err => noop,
    complete: () => {
      this.isLoading = false;
    }
  });
}

Answer №1

When determining a person's first and last name without specific guidelines, one approach is to consider the first word as the first name and everything else as the last name...

Building on this idea and implementing it in code...

const parseName = fullname => {
  const tokens = fullname.split(' ');
  const firstname = tokens[0];
  const lastname = tokens.slice(1).join(' ');
  return {
    firstname,
    lastname
  };
};

const compareNames = (a, b) => {
  const parseA = parseName(a);
  const parseB = parseName(b);
  return parseA.lastname.localeCompare(parseB.lastname);
};

let sorted = ["Mary Tyler Moore", "Madonna", "Erik The Great"].sort(compareNames);
console.log(sorted)

Another approach involves caching the parsed name information for objects, allowing easier access for future operations such as sorting...

const parseName = fullname => {
  const tokens = fullname.split(' ');
  const firstname = tokens[0];
  const lastname = tokens.slice(1).join(' ');
  return {
    firstname,
    lastname
  };
};

// Updated comparison function that uses the cached 'parsedName' property
const compareObjects = (a, b) => {
  return a.parsedName.lastname.localeCompare(b.parsedName.lastname);
};

// Assign each object a new parsedName property
const augmentedData = getData().map(o => ({ parsedName: parseName(o.display), ...o }));

let sorted = augmentedData.sort(compareObjects);
console.log(sorted);

// Function to retrieve sample data
function getData() {
  return [{
      "id": 2,
      "display": "Alen Geizer",
      "subDisplay": null,
      "attribute1": null,
      "attribute2": null
    },

    // Additional sample data entries...
    
  ]
}

By caching the parsed name, not only is efficiency improved, but potential inconsistencies arising from subjective interpretations of names are also mitigated within the application.

Answer №2

In the scenario where

a = [referencing previous context]
and the term "last name" refers to the string that comes after the last instance of a space, a possible implementation could be as follows:

const extractLastName = obj => obj.name.split(' ').pop();
a.sort((firstObj, secondObj) => extractLastName(firstObj).localeCompare(extractLastName(secondObj)));

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

Using Three.js with Webpack 5 and FBXLoader inline integration

I am currently working with Webpack 5 and attempting to provide a direct file path to my FBXLoader using the latest Webpack asset modules: const loader = new FBXLoader() loader.load('../assets/models/myModel.fbx', (object) => { ... }) // encou ...

How can you refresh the .replaceWith method in jQuery?

Is there a way to reset the .replaceWith function so that the html, css and javascript elements are restored to their original state? I am looking to have an icon replace the text when the user clicks on "contact", and then have the text return when the u ...

Extracting values from dynamically named properties in ES6 using object destructuring

let currentFilter: Product = { name: 'iphone', price: 30, createdDate: '11-11-2020' } My code is structured around a specific filter. The filter data is structured in the following format: I have a table with different filters. ...

AngularJS Multi-select Dropdown Filter Logic

Thank you for taking the time to review my query. Currently, I am working on an AngularJS UI-Grid project where I have incorporated a Multi-select Drop-down Menu for the "First Name" column. However, I am facing challenges in implementing the logic similar ...

Creating an Angular directive that shares a single scope while displaying multiple behaviors

I am facing a specific scenario with my directive where the refresh scope needs to be either an object or a function. How can I properly assign this to my directive? 1. Initial scenario <!--HTML--> <directive refresh="vm.refresh"> </dir ...

Merge JavaScript Functions into a Single Function

I am looking to streamline the following javascript code into a single function by utilizing an array of ids instead of repetitive blocks. Any suggestions on how to achieve this would be greatly appreciated. Currently, in my code, I find myself copying an ...

Issue with narrowing TypeScript arrays often encountered

When working with arrays of strings in my TypeScript code, I restrict the contents to certain letters by using a defined type like ("A" | "B")[] for letters such as A and B. However, when I have a function that takes an arbitrary array ...

Achiever.js - Incorporating incremental progress with half stars instead of whole stars

Hello there! I've been utilizing Rater.js in my current project, and so far it has provided me with satisfactory results. However, I have encountered a particular issue that I am struggling to resolve on my own. It would be greatly appreciated if you ...

Creating these three functions directly in the Parent Component instead of duplicating code in the child component - ReactJS

I am new to React and currently working on a dashboard page that includes a React Table. The page features a customize button that opens a popup with checkboxes to show/hide columns in the table. By default, all checkboxes are checked but unchecking a colu ...

Working with npm objects across multiple files

My goal is to integrate the npm package for parallax (lax.js) into my project. The documentation states that in order to initialize it, the following code snippet should be included: window.onload = function () { lax.init() // Add a driver that we use ...

What is the process for node_modules packages to access configuration files located in the project root directory?

I am currently developing an npm package that requires the ability to access configuration files from the project's root directory. I'm uncertain of the proper method for accomplishing this. For instance, Next.js has the capability to read ./p ...

While working with Ngrx/effects, an error with code TS2345 occurred. The error message stated that the argument is of type 'Product[]', which cannot be assigned to a parameter of type

When I compile my code, I encounter the following issue (despite not finding any errors in the browser console and the application functioning properly). An error occurs in src/app/services/product.service.ts(15,9): The type 'Observable<Product> ...

Having trouble with Ng-repeat not functioning properly on arrays of objects?

I have an array of objects that I fetched from the server. The query is working fine, but when I try to use the ng-repeat directive in my HTML view, nothing is being displayed. Why could this be happening? Here is the JavaScript code: $scope.companyList = ...

Obtain the leaf nodes from a combination of arrays and objects using Lodash

Here is the code structure I want to share with you before explaining my requirements. It displays the input array layout along with the desired outcome: [ { link: "someurl", name: "Foo", subCats: [ { link: "anotherurl", ...

How can data be transmitted to the client using node.js?

I'm curious about how to transfer data from a node.js server to a client. Here is an example of some node.js code - var http = require('http'); var data = "data to send to client"; var server = http.createServer(function (request, respon ...

Ways to transfer textfield input from HTML to servlet without the use of forms

I am currently developing an e-commerce website and I want to offer users the option to select a different shipping address: Shipping Details <input type="button" value="Same as billing address" style="color: #FFFFFF;" class="link-sty ...

Streamlining the process of implementing click events on elements selected by class using jQuery

Slowly but surely, I am gaining familiarity with jQuery and have reached the point where I desire to abstract my code. However, I am encountering issues when attempting to define click events during page load. Within the provided code snippet, my objectiv ...

Avoiding node_modules in Webpack 2 with babel-loader

After updating to Webpack 2, I've run into an issue with the "exclude" property in my "rules". It seems I can no longer pass "exclude" into "options". What is the correct approach to handling this now? Previously: { test: /\.js$/, loader: ...

The backend error message isn't triggering an alert!

My current issue involves using jQuery to execute a .php file. Whenever an error occurs in the backend, I want to display an alert message with the error details. However, when intentionally submitting with an error, no alert pops up and it just proceeds t ...

Utilizing Database values in .css files with Vue.js and TypeScript

I am currently working on extracting a color value from the database and applying it to my external .css files. I have searched extensively online but haven't found a satisfactory solution yet. Here is the JavaScript code snippet: createBackgroundHead ...