In Javascript, develop a function that takes in two arguments and output a two-dimensional array

I am looking to create a function that takes two arguments, rows and columns. The goal of this function is to generate a 2D array with the specified numbers and rows provided as input. Below is the code snippet for implementing this:

Feedback from seasoned developers would be greatly appreciated as I am still learning.

Despite scouring StackOverflow, performing Google searches, and reviewing various websites, I have been unable to find a solution.

function generate2DArray(A) {
            var columns = [];
            var rows = Math.sqrt(A.length);
            for (var i = 0; i < rows; i++) {
                  columns[i] = [];
                  for (var j = 0; j < rows; j++) {
                        columns[i][j] = A[i * rows + j];
                  }
            }
            return columns;
      }

Answer №1

To create an array from an object with the length and map the inner arrays, you can utilize Array.from.

const
    createArray = (l, w) => Array.from({ length: l }, (_, i) =>
        Array.from({ length: w }, (_, j) => i * w + j));

console.log(createArray(3, 2));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Your question statement does not align with the code you attempted. It seems like you are trying to convert a single-dimensional array into a 2D array. Your code is correct. However, the issue arises because Math.sqrt(A.length); may result in a float value and i * rows + j will then become a float as well, which cannot be used as an index in an array. Simply utilize Math.ceil() to resolve this problem

The code below provides two solutions for a function that takes both length and width arguments.

function create2Darray(A) {
     var columns = [];
     var rows = Math.ceil(Math.sqrt(A.length));
     for (var i = 0; i < rows; i++) {
        columns[i] = [];
        for (var j = 0; j < rows; j++) {
            columns[i][j] = A[i * rows + j];
        }
    }
    return columns;
}

console.log(create2Darray([1,2,3,4,5,6,7,8]))

A one-liner solution can also be achieved using nested map()

const array = (l,w) => [...Array(l)].map((x,i) => [...Array(w)].map((x,j) => (i*w) + j))
console.log(JSON.stringify(array(3,2)))

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

Is there a way to attach event listeners to dynamically inserted elements within a Google Calendar interface?

This particular issue is closely related to a few other questions: Jquery adding event listeners to dynamically added elements Add Event Listener for dynamically created particular element using jquery If you want to see a working example, check out thi ...

Animation of two divs stacked on top of each other

I am trying to replicate the animation seen on this website . I have two divs stacked on top of each other and I've written the following jQuery code: $('div.unternehmen-ahover').hover( function () { $('div.unternehmen-ahover' ...

Storing and Editing Collection of Elements

My latest project involves creating a basic web scraping tool that gathers information on apartment prices from a specific webpage. Each time the tool runs, it compiles an array of objects with details such as date, time, floor plan name, bed number, floor ...

Challenges arise when attempting to return an early resolution within promises in JavaScript

I have a function that determines further execution within itself and needs to use promises since it is asynchronous. An issue arises where the function continues execution even after resolving. Here's my code: function initializeApplication() { ...

Show either the abbreviated or complete form of the text

Initially, the default display should show the shortened version of each element (one line with "..." included). All items must consistently be shown in either the shortened or full-length version. If all items are in shortened mode - clicking on one item ...

What is the process for customizing a form in the "add event" feature of wdCalender?

I am looking to customize the form in wdCalendar to add events with fields like first name and last name instead of "what". I need to modify the quickadd function in jquery.calendar.js, which is triggered when a user clicks on the calendar to add an event. ...

Strings holding special arrangements of breaks in between

Currently, I am developing a portal that enables examiners to provide a problem statement, sample input, and sample output. However, I am facing an issue where the sample input/output values are stored as complete strings, causing line breaks to not render ...

What is the process for verifying the ongoing sessions within a particular set of classes?

I have a list of 10 items with varying active classes based on user interactions. I need to determine the number of sets of 3 consecutive active classes within the list. In the given example, there are 2 sets of 3 consecutive active classes: 4,5,6 and 8,9, ...

Error in vis.js network: hierarchical layout caused by node quantity

I'm encountering an unusual issue that I can't seem to resolve by referring to the vis.js documentation. My network has a fixed hierarchy with a specific level defined for each node. I have a total of 51 nodes, and everything looks like this: ...

Transformation of an Ajax array into an associative array

Currently, I am working on creating an API using Ruby on Rails and facing a challenge with sending an array through ajax. The task seems straightforward, but the issue arises when the array is received as an associative array instead of a regular one! Es ...

How can we determine the total number of mandatory fields in an AngularJS form?

Can you explain how to calculate the number of required fields in a form using AngularJS? In my form, there are two required fields (email and select view). I want to display the count on my page - showing 2 if email is filled, 1 if only email is filled, a ...

What could be causing this error to occur? I've already got node.js installed on my system

When I enter npm init in the Visual Studio Code - Insiders terminal, I get the following error message: npm init npm : The term 'npm' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the ...

"Exploring the magic of Vue.js and Three.js: A guide to seamlessly changing CSS style elements within an

I'm currently in the process of converting my Three.js project to Vue.js Within my Three.js scene, I have a 3D model with HTML points of interest attached to it. It is crucial that these points remain fixed to the model and consistently face the cam ...

A guide on leveraging *ngFor in Angular 4 to assemble a table featuring 2 columns in every row

I have an array of objects as shown below let columns = [ {id: 1, columnName: 'Column 1'}, {id: 2, columnName: 'Column 2'}, {id: 3, columnName: 'Column 3'}, {id: 4, columnName: 'Column 4'} ]; My ...

Excellent Methods for Implementing a Double Click Functionality in JavaScript for Mouse

Is there a way to make the mouse double click by itself using JavaScript? I need this functionality for a Selenium project that requires testing, but unfortunately Selenium does not provide an option for double clicking. Can anyone suggest how I can achiev ...

Enhancing specific child value in Firebase Database using JavaScript: Exploring Firebase Realtime capabilities

I have a database structure where I need to update the value of isseen to true when the sender is equal to "5". Here's an example of my database structure: Chats -LvuhnORi1ugp8U2Ajdq isseen: "false" message: "hi" receiver: "OX0pReHXfXUTq1XnOnTSX7moiG ...

This element is not suitable for use as a JSX component since its return type 'void' is not a valid JSX element. Please check the return type to ensure it is compatible with

I have been working on this code snippet: function searchData(searchWord: any) { if (originalData.length > 0) { if (searchWord !== "") { setDataList([...originalData.filter((svc: any) => ...

Choose particular content enclosed by two strings (across multiple lines)

Looking to use regex to extract specific text between two strings. For example: foo I have four toys bar //single line foo //multiline I have four toys bar foo I have three pets bar foo I have three pets bar How can I extract the text between & ...

In the middleware, the request body is empty, but in the controller, it contains content

Below is my server.js file: import express from "express"; import mongoose from "mongoose"; import productRouter from "./routers/productRouter.js"; import dotenv from "dotenv"; dotenv.config(); const app = expres ...

Arranging JSON based on values in an array using node.js

Seeking assistance with sorting a JSON object by specific keys within a node.js program. The task involves arranging the object in ascending order based on the "trip_miles" value when the "trip_name" equals CC, and then extracting only the id's as out ...