Combining Multiple Arrays into a Multidimensional Array

I'm struggling to find information on how to combine multiple arrays of the same length into a multidimensional array.

For example, I have three arrays:

array1 = [value1a1, value2a1, value3a1];
array2 = [value1a2, value2a2, value3a2];
array3 = [value1a3, value2a3, value3a3];

I want to merge them into a single multidimensional array like this:

multiArray = [
                [value1a1, value1a2, value1a3],
                [value2a1, value2a2, value2a3],
                [value3a1, value3a2, value3a3]
];

If you have any advice on the best method to achieve this, I would greatly appreciate it.

Answer №1

let multiArray = [];
multiArray.push(array1);
multiArray.push(array2);
multiArray.push(array3);

Learn more about Array.push()

Alternatively:

let multiArray = [array1, array2, array3];

Check out the JSFiddle example of the second approach

@MartijnOtto was correct in noting my previous mistakes. I have now corrected it with a new version on JSFiddle using this code:

let array1 = ["value1a1", "value2a1", "value3a1", "value4a1"];
let array2 = ["value1a2", "value2a2", "value3a2", "value4a2"];
let array3 = ["value1a3", "value2a3", "value3a3", "value4a3"];

let arrays = [array1, array2, array3];
let multiArray = [];

// initialize 2D array
for (let i=0; i<arrays[0].length; i++) {
    multiArray[i] = [];   
}
// fill values
for (let i=0; i<arrays.length; i++) {
    for (let j=0; j<arrays[i].length; j++) {
        multiArray[j].push(arrays[i][j]);
    }
}

result.innerHTML = JSON.stringify(multiArray, null, 2);

Edit: there was another minor error with indices. Fixed it in JSFiddle and code here to also work with unproportional array sizes (e.g.: arrays.length === 3 and arrays[i].length === 4.

Answer №2

function combineArrays() {
    var finalArray = [];
    for (var x = 0; x < 3; ++x)
    {
        var tempArray = [];
        for (var y in arguments) tempArray.push(arguments[y][x]);
        finalArray.push(tempArray);
    }
    return finalArray;
};

This custom function can merge multiple arrays as long as each array contains exactly three elements. The merging process follows the specifications outlined in the initial request.

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

Does Jquery AJAX send back raw data or HTML ready for use?

I'm currently developing a mobile app using Jquery Mobile. In order to populate the app with data, I need to make requests to an API and display the information within the app. At this point, I have two possible options: The API returns JSON data ...

The HTML file seems to be having trouble connecting to the JavaScript file

I am currently working on a small, fun website project and have an HTML file along with a JavaScript file in the same directory. However, my HTML seems to be unaware of the existence of my JavaScript file. It fails to execute the function during the load e ...

Python Scrapy: Extracting live data from dynamic websites

I am attempting to extract data from . The tasks I want to accomplish are as follows: - Choose "Dentist" from the dropdown menu at the top of the page - Click on the search button - Observe that the information at the bottom of the page changes dynamica ...

The random number generator often omits both the upper and lower limits

I am working with an array that contains letters from A to H. However, when using a random number generator, I have noticed that the letters A and H are rarely selected. How can I adjust my approach to make sure these two bounds are included more often? ...

Tips for transmitting an onChange function from a parent component to a child component in material UI

As a newcomer to react and material UI, I am currently working on developing a dropdown select component. My goal is to pass onChange functions to the component from its parent. Despite following the official documentation closely, I've encountered an ...

Unique ways to serialize an HTML element efficiently: JavaScript tricks

Is there a way to store a reference of an HTML tag for future use? For instance, if I click on a div and save a pointer to that div in JavaScript, is it possible to serialize this pointer and then de-serialize it to use in another part of the web applicat ...

VueJS not refreshing DOM after AJAX data modification

Utilizing Vue.js to make changes to my DOM, I have implemented the fetch_data() method. This method attempts to update data.messages to display 'Love the Vue.JS' once the AJAX call is successfully completed. The AJAX call executes successfully a ...

Struggling to populate a nested array in a dropdown using AngularJS

I am currently working on populating JSON data into a dropdown list, specifically focusing on main category, sub category and sub sub category. Successfully managed to populate the main category and sub category, but facing challenges with populating subsu ...

Using jQuery, retrieve the "select" element within a specific row of a

I am working on a table row that has the following HTML structure: When the user interacts with the "Name" field, I trigger the "select" event and pass it to the nameDropChanged function. Once I have a reference to this select element, I need to change th ...

Storing and Retrieving Multiple Data with localStorage

I need assistance with modifying my code. I have an input field labeled "mail" and I am trying to store email addresses and corresponding IDs in local storage. The email address should be taken from the "mail" input field while the ID should increment each ...

Image loading failure detected in ReactJS

In my current project using Reactjs (Nextjs framework), I encountered an issue where I am unable to display an image on a page without specifying the "height" and "width" attributes in the Image tag. I attempted the following code snippet but the image is ...

Attempting to execute the .replace() method but encountering difficulties

Looking for help with some HTML code: <li><a href="#" class="lstItem">Testing jQuery [First Bracket]</a></li> <li><a href="#" class="lstItem">Loving jQuery [Second one]</a></li> I need to remove the text in ...

Debugging Success Message Display Issue in JavaScript

$.ajax({ type: "POST", url:'/saveLayout', data: {id : layoutId, section : arrSection}, success: function(response){ $('#successMsg').addClass("errorBox"); document.getEleme ...

Is Local Storage compatible with phonegap?

I am looking to integrate local storage into my phonegap application in order to store an array of data. Here is a snippet of my code: <div data-role="collapsibleset"> <div data-role="collapsible"> <h3>LOG ...

web browser editing tool

Do you know which library was utilized to create this JSON editor? https://i.sstatic.net/kGpGz.png You can find it at . The editor efficiently checks the syntax and shows errors when necessary. ...

What are the best practices for managing user forms and uploading files?

How should data in text fields and file upload fields be handled according to best practices? This question is a more generalized version of one I previously asked, which can be found here. Let's consider the scenario of a user registering an accoun ...

Trouble accessing environment variables within a React application, specifically when using webpack's DefinePlugin in a Dockerfile

I can't figure out why console.log is printing undefined. The files Makefile, config.env, webpack.config.js, and package.json are all located in the root of my project. Makefile: docker-run: docker docker run -it --env-file config.env -p "80:80" ...

The layout in Nextjs _app does not stay constant; it refreshes with each page change

After creating a _app.js file: const MyApp = ({Component, pageProps}) => { const getLayout = Component.getLayout || ((page) => <Layout>{page}</Layout>) return getLayout(<Component {...pageProps} />) } export default ...

PHP variables that are constantly changing

I recently developed a website that showcases random entries from a database to viewers. Here is the current code snippet I am using: $records = "SELECT * FROM xxx"; $records_query = mysql_query($records); $num_records = mysql_num_rows($records_query); $i ...

There was an error during module build process: ReferenceError occurred due to an unrecognized plugin "import" specified in "base" at position 0

I have encountered an error while working on my ReactJS project using create-react-app. The error arose after I added and removed a package called "react-rte". Now, every time I try to start my project, I get the following error: Error in ./src/index.js Mo ...