Generate a JavaScript or TypeScript 2D array of any size with just a single line of code

Is there a more efficient method to create an m×n 2d array in JavaScript or TypeScript, rather than using nested arrays?

arr = [[0, 0], [0, 0]]

An alternative approach is:

arr = new Array(m).fill(new Array(n).fill(0))

However, this results in all rows being the same array:

arr[1][2] = 5
console.table(arr)
(index) 0 1 2
0 0 0 5
0 0 0 5

To avoid this issue, you can use the following syntax:

arr = [...new Array(2)].map(() => new Array(3).fill(0))

While functional, some might view this as inelegant. Are there better options in JavaScript or TypeScript for creating 2d arrays?

Answer №1

Consider using Array.from

Create a new array with Array.from({length: 3}, () => Array(3).fill(0))

Set a value at index [1][2] to 5

Print the modified array
console.log(arr)

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

Unable to figure out why information is not being transferred to an array through Mongoose

Seeking assistance as I am unable to figure out how to place a set of information into an array named "teamDetails". Here is the relevant /post item from server.js: app.post('/create', (req, res) => { console.log('Post command receiv ...

How to programmatically close a colorbox using an ASP.NET form's Submit button within an iframe

I've looked at other similar questions, but I just can't seem to make this work. I want to close the colorbox iframe when a .NET Button form within the iframe is clicked. <script type="text/javascript"> $(document).ready(function() { ...

Winston prefers JSON over nicely formatted strings for its output

I have implemented a basic Winston logger within my application using the following code snippet: function Logger(success, msg) { let now = new Date().toUTCString(); let logger = new (winston.Logger)({ transports: [ new (winsto ...

What is the most efficient method for comparing vectors in C++?

Is there a quick method to determine if two vectors are equal in c++? I am currently seeking the most efficient way to check if any row matches any column of a matrix, without having to compare each element individually and exit the loop when inequality i ...

Leveraging the package.json file to execute a separate script within the package.json file

Within my project's package.json file, I have a script called npm run script1. Additionally, my project includes a private npm package as a dependency, which contains its own set of scripts in its package.json file, including one named script2. My goa ...

When you click on the column header to sort, the corresponding column row changes color in JavaScript

https://i.sstatic.net/4ELuv.jpg When a user clicks on a column to sort, the color of the column changes or highlights the row. In my tablesorter with ascending and descending sorting capabilities, I want the sorted column to change colors for better visib ...

Generate a unique JavaScript token using user-specific information

I am in need of a unique identifier for users that can be generated without conflicting with other users' tokens. One idea I had was creating a token using the MD5 hash of navigator.userAgent + new Date().getTime(). However, I don't want to use a ...

Having trouble accessing data from MongoDB using Node.js and Express

Looking to retrieve data from Mongo DB using Node JS and Express JS? After creating a mongoose schema and exporting the module, you may encounter an issue where running the function returns an empty JSON object. Take a look at the code snippets below: Thi ...

Troubleshooting: Issue with v-link to classname in Vue.js

This is the code I am working with: <div v-link="'/work/' + {{data.useClass}}" class="itemImg {{data.useClass}}"> When rendered in the browser, it looks like this: <div class="itemImg x50"> The expectation is that class="itemImg { ...

Issue with validating the date picker when updating user information

Trying to manage user accounts through a dialog form for adding and updating operations, where the type of operation is determined by a variable injected from the main component. Encountered an issue while launching the update process - the date picker tri ...

A step-by-step guide on exporting data to an Excel file using an API

Dealing with an Angular datatable containing over 50k records can be a challenge when trying to export to Excel. The process takes a lot of time and causes the browser to become unresponsive. If anyone knows how to export large data sets to Excel without d ...

Instructions on incorporating a created object from a class into an array by utilizing a method specifically made within that class

After implementing a Book class which includes a method to add a single object to an array upon clicking a button, I noticed that when the button is clicked, it adds the button itself rather than the expected object. See the code snippet below: class Book ...

Is it possible to create a button function in HTML that can alter the CSS image tag?

Is there a way I could create a function that can retrieve a value, update an image source, and then incrementally select another value? It would be incredibly helpful if you could provide a reference where I could learn how to do this or explain it in det ...

Module augmentations do not allow for exports or export assignments

import { Request as ExpressRequest, Response as ExpressResponse } from 'express'; declare module 'kvl' { export = kvl; } declare const kvl: { ValidationDone:(param:(error: any, response: ExpressResponse) => void) => void; ...

Switch up the default font in your Nuxt 3 and Vuetify 3 project

I've been doing a lot of searching on Google, but I can't seem to find the solution. It seems like the challenge might be that the Nuxt 3 + Vuetify 3 combination isn't widely used yet? My current task is to implement a custom default font. ...

Executing POST and GET requests in NODEJS through client-side scripting

Currently, I am working on a NodeJs project that involves a system where a user triggers an action by clicking a button on the User Interface. I would like to save the user's history in the database as well, recording which commands or buttons they ha ...

Tips for adjusting the property of an object that has been added to an array?

I have created an object. { "heading": [{ "sections": [] }] } var obj = jQuery.parseJSON('{"header":[{"items":[]}]}'); Then I add elements to the sections var align = jQuery.parseJSON('{"align":""}'); obj["he ...

Deactivate background hover effects for bar charts in Recharts

Is there a way to disable the gray background that appears when hovering over bar charts in Recharts? I'm using version 1.4.1 and my code looks like this: import React from "react" // Recharts import { Bar, BarChart, CartesianGrid, ResponsiveContain ...

Error occurs in Azure Function Linux Nodejs when trying to use @azure/storage-blob as it cannot read the property 'startsWith' of undefined

While testing my Azure Nodejs Linux function locally, I encountered this issue with the code snippet below: import { BlobServiceClient } from "@azure/storage-blob"; const connectionString = process.env[ "AZURE_STORAGE_CONNECTION_STRING&qu ...

Troubleshooting the integration of Text Mask Library with Vue - issue: no export named 'default' available

I was able to implement the vanilla JavaScript version: var maskedInputController = vanillaTextMask.maskInput({ inputElement: document.querySelector('.myInput'), mask: [/\d/, /\d/, '/', /\d/, /\d/, '/ ...