Creating a multi-dimensional array in JavaScript by combining and rearranging data from linked arrays

I have an array of data retrieved from my database that looks like this.

["John", "Seth", "Eben"]["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f79d989f99b793989a969e99d9909881d9909f">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f083958498b0949f9d91999ede979f86de9798">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1b7e797e755b7f74767a7275357c746d357c73">[email protected]</a>"]`["0212225252", "0201115555", "0201115556"]

Although these are separate arrays, the data in them corresponds to each other - name, email, phone number. I want to organize this data into a multidimensional array while maintaining the relationships between the arrays. For example:

["John", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6d070205032d0902000c0403430a021b430a05">[email protected]</a>", "0212225252"]

["Seth", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a2d1c7d6cae2c6cdcfc3cbcc8cc5cdd48cc5ca">[email protected]</a>", "0201115555"]

This pattern continues for the remaining data entries. I've attempted various methods such as push and merge, but I seem to be struggling due to my limited JavaScript skills. Additionally, I already have a solution for displaying the resulting data in an HTML table using test dummy data. Any assistance on restructuring the array is highly appreciated. Thank you.

Answer №1

assuming that the corresponding indexes in each array will always be linked.

let names = ["Alice", "Bob", "Eve"],
  emails = ["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="58d8cfcac3e4dfd5dddada98d2dfded7ccc7dbdade9cdcdc60ddfcec7">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="392b37252403212a23373a31293c373a30271c2535292b21f01e373a21262d31392420292026">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7b110210150903171613141349041605020c05021351011c070c10170e01080806015d101417">[email protected]</a>"],
  phones = ["0213334444", "0202226666", "0203335555"],
  array = [];

for (const i in names) {
  array.push([names[i], emails[i], phones[i]]);
}

console.log(array);

Answer №2

To solve this problem, employ a loop:

let names = ["John", "Seth", "Eben"];
let emails = ["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a6ccc9cec8e6c2c9cbc7cfc888c1c9d088c1ce">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cebdabbaa68eaaa1a3afa7a0e0a9a1b8e0a9a6">[email protected]</a>",
"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cfaaadaaa18faba0a2aea6a1e1a8a0b9e1a8a7">[email protected]</a>"];
let phones = ["0212225252", "0201115555", "0201115556"];

let matrix = [];
for (let i = 0; i < names.length; i++) {
  matrix.push([names[i], emails[i], phones[i]]);
}

console.log(matrix);

Answer №3

const x = ["Mary", "Luke", "Ella"]
const y = ["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6b81858c8aa49984868a8285c5848c858dc4c7848986">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="137274746a525672707c7473337a720a737c">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="74212736383517">[email protected]</a>"]
const z = ["0312345678", "0365478952", "0378294621"]

function combine(x, y, z) {
  const namesList = JSON.parse(JSON.stringify(x));
  const emailsList = JSON.parse(JSON.stringify(y));
  const phoneNumbers = JSON.parse(JSON.stringify(z));
  return namesList.map((item, index) => [item, emailsList[index], phoneNumbers[index]])
}

console.log(combine(x, y, z))

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

Dividing a sequence of characters into individual words and duplicating them

I'm currently developing a program to parse information from a file in the following format: NODE: label Buenous Aires:x=131.3456:y=-48.783 My goal is to split each line into an array containing the label, x value, and y value. I have explored using ...

Formatting currency in Spanish using intl.NumberFormat displays inaccurate results

Based on my research, the output for es-ES and de-DE locale should be different. (I consulted with a Spanish colleague about this issue, and he mentioned that there is indeed a decimal after thousand in Spain) var number = 1000; console.log(new Intl.Numbe ...

React: Introducing the latest router feature post-login

I'm facing an issue with the Router in React. After a successful login, I am changing the type state in Redux from 0 to 1. However, when I try to make a switch in my App file, I encounter an error. Warning: [react-router] You cannot change <Router ...

In three.js, a full rotation on the Y axis is not achievable for cubes

My low poly world features gravity added with raycasting to the character. Now, I am looking to incorporate another raycaster in front of the character, specifically the pointer lock controls, to enable walking on non-flat surfaces. This raycaster would al ...

Working with SQL databases using Javascript Objects in Javascript

I am working with a basic client-side Sqlite database using Google Gears for storing the properties of a javascript object. I am not concerned about normalization because my object contains various types of fields that would complicate the process anyway. ...

Struggling to access an element within the Vue state (Vue.js/JS/TS)

Encountered a challenge today while working with Vue. In a function, I cannot retrieve an element from a state. However, when I use console.log() to check the state, the element is present. Any suggestions on how to rectify this issue? Here's the re ...

I'm encountering an issue during the code compilation process. Can someone please point out where I am making a mistake and provide guidance on how to resolve it?

I encountered an error in the terminal while attempting to compile the code, but I am having trouble understanding the reason for it. Code: const express = require("express"); const app = express(); console.dir(app); Error: https://i.sstatic ...

One might encounter undefined JSON keys when attempting to access them from a script tag

During my attempts to load a specific Json using an Ajax GET request and then parsing it, I encountered an issue when trying to access the Json key from an HTML script tag, as it returned as undefined. To troubleshoot this problem, I decided to log all th ...

Leverage TypeScript Enum along with PropTypes to declare the properties of a React component

Upon having the Component and utilizing a TypeScript Interface for defining its props: interface Props { headerType: DROPDOWN_MENU_TYPE, //DROPDOWN_MENU_TYPE is enum headerContent: SVGClass isReverse: boolean; }; const MyComp: React.FunctionC ...

Implementing the useEffect hook in React to iterate over JSON data and update the state

Having trouble implementing job location filtering ("remote"/"in-person"/"hybrid") for my personal project. As a beginner in programming, I've spent quite some time troubleshooting the fetchLocationData function and passing URLSearchParams. I anticipa ...

What is the best way to extend the functionality of npm script with command line arguments

After defining multiple scripts in my package.json file, I encountered an issue when attempting to run the $ npm run lint:fix command. The argument --fix did not get passed down to ./node_modules/.bin/standard, resulting in an error. { "name": "project" ...

Ways to modify CSS using JavaScript

Can anyone assist me with a custom CSS code that I found? It looks like this: header.type-2:not(.fixed-header) nav>ul>li>a{ color:#000; } I've been trying to change the color to #fff using JavaScript, but haven't had any success yet. ...

What causes the undefined value of "this" in the Vue Composition API setup function?

A Vue component I've created is using v3's composition API: <template> <input type="checkbox" v-model="playing" id="playing" @input="$emit('play', $event.target.value)" /> <labe ...

Is there a way for me to retrieve the element that is linked to the ng-disabled attribute?

Is there a way to access the element with the ng-disabled attribute inside the function without passing it as a parameter? Here is the HTML element: <input class="needsDisabling" ng-disabled="isFieldDisabled()" type="text"> The isFieldDisabled fu ...

Ways to serve JSON response following a 400 error code

After a user submits incorrect form details, such as an invalid username or blank email address, I make an Ajax request to my REST API. The response data I receive is structured as follows: HTTP 400 Bad Request Allow: POST, OPTIONS Content-Type: applicati ...

The JOptionPane component appears to be distinct

When utilizing the code provided, I have noticed that the appearance of the JOptionPane varies depending on the number of items within the array. Sometimes it displays a drop-down scrolling list (similar to a JComboBox), while other times, when the array c ...

Retrieve the element that was clicked during the show.bs.collapse event in Bootstrap 4's Collapse feature

Looking for a solution to dynamically inject data into a collapsing panel based on the element that triggered it? I need to capture the clicked element when the panel is about to be displayed. Here is the HTML structure: <div class='container&apos ...

AngularJS not detecting string values in arrays

I've run into a frustrating issue while working on an accounting project. When I input values into text boxes and click the Add Person button, the values are successfully added. However, when I attempt to save these values to the database by clicking ...

Embed a physical entity within another physical entity

On my webpage, I have 2 toggle buttons - "Leaderboard" and "MedalTally". The layout looks like this: https://i.sstatic.net/IohqA.png Here are the codes for the above page: *, *:before, *:after { box-sizing: border-box; } html { overflow-y: scrol ...

Utilizing a character array to reverse a string

After working on a program to reverse a string using a character array, I encountered a common issue that I couldn't resolve. Here is my code: #include<iostream> void reverseString(char *str) { char *end; end = str; if(str) { while ...