Attempting to form a complex array structure within a function

I am currently working on a task that involves converting three separate inputs into a multidimensional array.

Although I am aware that users can input up to 8 values, my existing code is generating empty arrays. I need to find a way to dynamically modify my code in order to avoid this issue. Below is the function that I have created:


a = 'Hi' 
b = 878
c = 654

function convertToTable(a, b, c) {
            for (var i = 0; i < 8; i++) {
                result[i] = new Array(8);
            }

            result[0][0] = a[0];
            result[0][1] = b[0];
            result[0][2] = c[0];

            result[1][0] = a[1];
            result[1][1] = b[1];
            result[1][2] = c[1];

            result[2][0] = a[2];
            result[2][1] = b[2];
            result[2][2] = c[2];

            result[3][0] = a[3];
            result[3][1] = b[3];
            result[3][2] = c[3];

            result[4][0] = a[4];
            result[4][1] = b[4];
            result[4][2] = c[4];

            result[5][0] = a[5];
            result[5][1] = b[5];
            result[5][2] = c[5];

            result[6][0] = a[6];
            result[6][1] = b[6];
            result[6][2] = c[6];

            result[7][0] = a[7];
            result[7][1] = b[7];
            result[7][2] = c[7];

            for (var i = 0; i < 8; i++) {
                for (var j = 0; j < 3; j++) {
                    document.write(result[i][j] + '&emsp;');
                }
                document.write('</br>');
            }

        }

The expected output of the array should look like the following if a = 'Hi', b = 878, and c = 654:

However, please note that 'a', 'b', and 'c' are arrays storing their own data. Each element in 'a' will be a string, while each element in 'b' and 'c' will be integers.

Hi 878 654

Hi 878 654

Hi 878 654

ETC....

Answer №1

Here is the solution that will provide you with the desired outcome:

const a = ['Hi', 'Hi', 'g', 'j', 'm', 'p', 's', 'v'];
const b = ['900', '900', 'h', 'k', 'n', 'q', 't', 'w'];
const c = ['654', '654', 'i', 'l', 'o', 'r', 'u', 'x'];

function createTable(a, b, c) {
  let length = a.length;
  if (length !== b.length || length !== c.length) {
    console.warn('arrays must be of equal length');
  }

  [...Array(length)].map((_, index) => {
    document.write(`${[a[index], b[index], c[index]].join('&emsp;')}<br/>`);
  });
}

createTable(a, b, c);

I hope this explanation clears things up for you,

Answer №2

I had a breakthrough thanks to my employer's collaborative brainstorming, which guided me towards the solution I needed. Here is what we came up with:


function createPopulationTable(states, populations, growthRates) {
    document.write('<table cellspacing="5" cellpadding="1" border="1"><tr><th>State/Territory</th><th>Population</th><th>Growth Rate</th></tr>')            
    for (var i = 0; i < states.length; i++) {
        document.write('<tr><td>' + states[i] + '</td><td>' + populations[i] + '</td><td>' + growthRates[i] + '</td></tr>');                
    }
    document.write('</table><br><hr>');
}

Answer №3

var arr_a = [], 
    arr_b = [], 
    arr_c = [];

for (var i = 0; i <= 7; i++) {
  arr_a[i] = 'Hi';
  arr_b[i] = 878;
  arr_c[i] = 654; 
}


exitToTable(arr_a, arr_b, arr_c);

function exitToTable(a, b, c) {
            let tester = [];

            // Creating multi-dimensional array
            for (let x = 0; x < a.length; x++) {
                tester[x] = [];
                tester[x][0] = a[x];
                tester[x][1] = b[x];
                tester[x][2] = c[x];
            }

            // Printing the multi-dimensional array
            for (let i = 0; i < tester.length; i++) {
                for (let j = 0; j < 3; j++) {
                    console.log(tester[i][j]);
                }
            }

            console.log(tester);
        }

This is an illustration on creating a Multi-dimensional Array in JavaScript

        var array = [];
        var array2 = ['text-1', 'text-2'];
        var array3 = ['item-1', 'item-2'];

        array.push(array2);
        array.push(array3);

        console.log(array);
        
        console.log(array[0][1]);

Find out length of array: array.length.

            var array = [];
            var array2 = ['text-1', 'text-2'];
            
            array[0] = array2;
            console.log(array);

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

Styled-components does not generate a style tag as output

After creating a new project in React with Webpack, I decided to experiment with Styled Components. In my index.js file, the code is structured like this: import React from "react" import ReactDOM from "react-dom" import Page from "./site/Page" import s ...

Contrasting the effects of using state separately versus together within ReactJS

I define my state like this: const [state,setState] =useState({ type:false, imageSrc:'', captionImage:'', showImage:false, }); When I update the state, I do it like this: setState({type:true}); setState({captionImage:& ...

Why isn't the connect.use() function working in Node.js?

I have been studying and applying examples from a book to learn Node.js. While replicating one of the examples, which involved creating a middleware, I encountered an error when trying to run the JavaScript file. The error message stated "undefined is not ...

the attempt to send an array of data to the $.ajax function was unsuccessful

let myArray = []; myArray.push(someValue); let requestData = { action: myAction, array: myArray }; $.ajax({ type: "POST", data: requestData, url: requestUrl, success: handleSuccess, error: handleError }); When ...

What could be causing the code to output more than 6 elements?

#include <stdio.h> int main() { int numbers[] = {5, 10, 15, 20, 25}; int length = sizeof(numbers) / sizeof(numbers[0]); int newNum, position; printf("Enter a number to insert in the array: "); scanf("%d", &newNum); printf("En ...

Tips for implementing an element onClick change within a Redux container using React.js

After coming across a similar question by another user on this link, I found the answer quite clear. However, if you're dealing with a redux container, the states are transformed into props via the mapStateToProps function. So, my query is: how shoul ...

Place a check mark in the corner of the button

I am looking to add a checkmark on my button in the right corner. I have set the input value and it displays a button with a check mark, but I want it to be positioned in the right corner. .buttoner{ background-color: #4CAF50; b ...

Ensure that the child iframe is referencing its own content, and not that of the parent iframe

What I have is a nested Iframe setup as shown below <iframe id="is Static"> stuff <iframe id="Is Dynmic> <html>...</html> <body id="This is thebody"> other stuff </body> I am trying to listen for the mou ...

There was an error thrown: Unable to assign the 'type' property to a null value

When using the master page in ASP.NET, I encountered an error message in the Chrome browser's inspection tool console. Uncaught TypeError: Cannot set property 'type' of null at myFunction (StudentPassword.aspx:258) at HTMLInputElement.oncli ...

Can a node package be imported from a different package?

If I recently installed the react-native-gifted-chat package from npm and discovered it includes another package, how can I access the uuid package located within that package? This is what's inside my node_modules folder: https://i.sstatic.net/wf9t ...

Regain the cursor focus on a text input field once it has been disabled and re-enabled using AngularJS

In my code, I have implemented an input field along with a $watch function that triggers a server request when the scope variable changes. While the server request is being processed, I disable the input field. However, once the request is complete and the ...

How can one efficiently navigate through extensive functions without risking surpassing the stack limit?

I am currently developing an application in Node.js that requires numerous configuration and database calls to process user data. The problem I am facing is that after reaching 11,800+ function calls, Node throws a RangeError and exits the process. The er ...

Adding a space after a comma automatically upon saving changes in VSCode

Whenever I input code (t,s) into the system and make changes to it, it automatically transforms into (t, s) with an added space after the comma. Is there a way to avoid VScode from adding this extra space on its own? ...

Why isn't the close button in jQuery working on an Asp.net page?

My current project involves working with Asp.net and C#. I am facing an issue where I click on a button to display a message in a popup box, but when I try to close the popup by clicking the close button, it does not close. Here is the syntax for the aspx ...

The array_mutisort functionality seems to be malfunctioning

Here is the code snippet that I am using: array_multisort($year, SORT_ASC, $wpjobus_resume_work); // Display sorted array. echo '<pre>'; print_r($wpjobus_resume_work); The values in the year variable are: 1990 1995 2013 However, th ...

Exploring Object to Retrieve Links in React

Upon receiving an API request, I am presented with the following external links: externalLinks : { website: { _links: { self: { rel: 'self', method: 'get', href: 'http://w ...

During the installation process of Next JS, I faced a challenge that hindered

While setting up NextJS, I ran into the following issue: D:\Codes\React\Learn>npx create-next-app npm WARN using --force Recommended protections disabled. npm WARN using --force Recommended protections disabled. npm ERR! code E404 npm ERR ...

How can I use VueJS and Vue Router to generate a details page for a list item?

I am currently working with a list of items sourced from a JSON file and looping through them. However, I want to create individual details pages for each item using VueRouter. Any advice on how I can accomplish this? I am facing difficulties in passing t ...

Using Node JS to pass variables to the client

Currently, I am utilizing Node JS and Express for my server-side needs. In my server-side code, I pass a variable (sources) to my EJS template. Part of this variable is used to populate a list on the webpage. However, when a user clicks on an item in the ...

Combining strings within a string after a specific word with nested Concatenation

In a given string variable "str," I am looking to concatenate another string between "InsertAfterMe" and "InsertBeforeMe". str="This is a string InsertAfterMe InsertBeforeMe" s1="sometext" s2="soMoreText" aList=[1,2,3,4,5] The concatenated string shoul ...