In JavaScript, split the array containing both first and last names into separate variables for first and last name

Looking for a solution to split an array element in a web template, where the size of the array varies per page. The array is in the format: ['John gray','Matt jones', 'Frank white']. The goal is to separate this array into two arrays regardless of its size - one containing the first names: ['John','Matt','Frank'] and another containing the last names: ['gray','jones','white']. While the split() method works for strings, I have not found much information on splitting arrays in this manner. Any suggestions or ideas?

Answer №1

To separate the names in an array, iterate through each name and use the split function to divide them into two different arrays.

let names = ['Sarah Smith', 'Emily Jones', 'Michael Brown'];
let firstNames = [];
let lastNames = [];
names.forEach(name => {
    let splitted = name.split(" ");
    firstNames.push(splitted[0]);
    lastNames.push(splitted[1]);
});

Answer №2

Instead of dividing arrays, you should focus on breaking down the array containing strings

var collection = ['John gray','Matt jones', 'Frank white'];
const [firstNames, lastNames] = collection
    .map(v => v.split(' ')) // break down each string
    .reduce((r, v) => [[...r[0], v[0]], [...r[1], v[1]]], [[],[]]); // create an array of arrays for first and last names
console.log(firstNames, lastNames)

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

Reverse the Angular component to AngularJS

I'm currently working on downgrading an Angular component for use in an AngularJS app. To test this, I created a simple Angular component: // my-test.component.ts @Component({ selector: 'my-test', template: '<h1>Hello Wor ...

What is the reason for the delay in the firing of this document.ready event

Similar Question: Understanding window.onload vs document.ready in jQuery I seem to be encountering a problem: I have an image on my webpage that is relatively small. I also have a JavaScript function that dynamically sets the height of the left sideb ...

Is it possible to execute custom JavaScript code in an R Jupyter notebook?

Within my Jupyter Notebook, I am working with the R programming language and would like to integrate javascript functions into it. I'm aware that there are libraries in javascript that can be called from R, but I haven't been able to find any ex ...

Is it possible for two distinct devices to generate the same HWID using Pushwoosh Cordova API?

Our app relies on HWIDs generated by Pushwoosh to distinguish between devices. After reviewing traffic logs, I noticed a peculiar pattern of what appears to be the same device sending HTTP requests from various ISPs within short time intervals. It seems t ...

Frustratingly Quiet S3 Upload Failures in Live Environment

Having trouble debugging a NextJS API that is functioning in development (via localhost) but encountering silent failures in production. The two console.log statements below are not producing any output, leading me to suspect that the textToSpeech call ma ...

The PUT rest service does not function in AngularJS version 1.0.8

I am facing an issue with my AngularJS application that has a CRUD Rest service. While the Create, Read, and Delete methods are functioning properly, the PUT method is not working. I have searched on Stackoverflow and found similar problems with accepted s ...

What is the best way to preserve an apostrophe within a variable in JavaScript without it being replaced?

How can I send the value of NewText in its original form from .cs code using an ajax call? **var NewText ="D'souza";** $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: " ...

What is the maximum file size that the data link is able to store?

For instance, a file like an image, video, or sound can be saved in the data link Take an image for example, it may be stored with the initial link: data:image/jpeg;base64,/..... followed by various characters. But, is there a specified size limit at whic ...

What happens when a JavaScript variable is used inside the $.ajax function and returns null?

I've come across numerous questions that are similar to mine, but unfortunately, I haven't been able to find a solution! My issue involves attempting to open a PHP file while passing certain Javascript variables into the URL using $.ajax. However ...

Show a malfunction with the `show_message` function

How can I show the die() message in if($allowed) in the same location as the move_uploaded_file result? <?php $destination_path = $_SERVER['DOCUMENT_ROOT'].'/uploads/'; $allowed[] = 'image/gif'; $allowed[] = ' ...

Change the size of window using jQuery

I have implemented a tooltip that can appear in two positions: top and bottom. I am trying to achieve this using jQuery resize function. The issue I am facing is that when the user resizes their browser window to less than 768px, the tooltip should appea ...

What is the best way to combine multiple arrays in Swift?

I currently have multiple classes defined as follows: class A {} class A1 : A {} class A2 : A {} class A3 : A {} class A4 : A {} class main { var a1 : A1 var a2 : A2 var a3s : [A3] var a4s : [A4] func getAll() -> [A] { ...

Creating a 2D integer array within a struct in the C programming language

I define the struct at the beginning of the program: struct roomData { float widthFeet, widthInch; float lengthFeet, lengthInch; char roomName[100]; int roomNumberOfType; char roomType[6]; //char of room type int roomStock[101][6]; //for stori ...

In Vue3, have you ever wondered why the $emit function seems to work fine before a promise fetch,

https://i.sstatic.net/yJmDY.jpg I have encountered an issue while attempting to pass the result of a promise fetch from a child component to a parent component using emit. Strangely, the emit function was working perfectly fine before the $fetch operation, ...

What is the process for exporting dynamic paths with the NextJS app using static methods

My webpage is located within the directory src/app/c/patient/[id]/page.tsx. Everything is functioning correctly when deployed, but I'm trying to export it to a js bundle for use with the Capacitor Android/iOS app. However, I encountered the following ...

Adjust the width of the TinyMCE Editor to automatically resize based on the content being

Is it possible for TinyMCE to adjust the content within an absolutely positioned container and update the width while editing? <div class="container"> <textarea>This is my very long text that should not break. This is my very long text tha ...

What is the benefit of writing in this manner?

Additional Module Insights available on redirectmodulenotes.com. Here is an example of how a module can be written: define(["require", "./another/name"], function(require) { var mod = require("./another/name"); }); Alternatively: define(function(req ...

Customize Material UI (MUI) Autocomplete with preset initial selections

My goal is to develop a unique MUI Autocomplete feature that showcases a series of numbers from 1 to 50. Upon user selection, the component should initially only show numbers 1, 6, 10, 12, and 24. If the user inputs '1', it should then display al ...

Fading Out with JQuery

My page contains about 30 same-sized divs with different classes, such as: .mosaic-block, .events, .exhibitions, .gallery, .sponsors, .hospitality, .workshops, .lectures { background:rgba(0, 0, 0, .30); float:left; position:relative; overf ...

Experiencing issues with passwords in nodemailer and node

Currently, I am utilizing nodemailer in conjunction with Gmail and facing a dilemma regarding the inclusion of my password. The predicament stems from the fact that my password contains both single and double quotes, for example: my"annoying'password. ...