Exploring 2D Arrays in ECMAScript 6

In my quest to avoid using traditional for loops, I am searching for a method to generate and populate 2D arrays using ES6. The goal is to have an array filled with all 0s. While I've attempted various strategies, the following code demonstrates one approach:

var [r, c] = [5, 5]; 
var m = Array(r).fill(Array(c).fill(0));

Although this code works, it results in multiple instances of the same array being created. Even attempting to use slice() doesn't resolve this issue:

Array(r).fill(Array(c).fill(0).slice());
.

Another strategy involved creating empty arrays and then iterating through them. However, I encountered a new challenge - you cannot use forEach() or map() on an empty array, and looping efficiently through a populated array proved to be problematic.

Am I overlooking something here? Are numerous for loops truly the most effective solution? This approach seems convoluted and unnecessarily lengthy. Any assistance would be greatly appreciated.

Answer №1

This method did the trick for me:

let [x, y] = [8, 8]; 
let grid = Array(x).fill().map(()=>Array(y).fill(0));

The key is to populate it with a temporary value in order to iterate through it smoothly.

Answer №2

To generate arrays filled with zeros, you have a couple of options. One way is to use the Array.from method along with the fill method inside a callback function.

const arr = Array.from(Array(2), () => Array(5).fill(0))
console.log(arr)

Another approach is to create an array that specifies the number of elements in each sub-array, and then use the map and fill methods accordingly.

const arr = [5, 5].map(e => Array(e).fill(0))
console.log(arr)

Answer №3

If you require a similar outcome with undefined for each value, this method is also effective.

const x = 100;
const y = 100;
const grid = [...new Array(x)].map(() => [...new Array(y)]);

To populate the array, simply map the inner value. This will create an array filled with 0 for each value.

const x = 100;
const y = 100;
const grid = [...new Array(10)].map(() => [...new Array(10)].map(() => 0));

Answer №4

function createArrayOfArrays(n) {
  return Array.from(Array(n), () => Array(5).fill(0));
}

const newArray = createArrayOfArrays(3);

console.log(newArray);

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

Incorporate the operating hours of a Business

If I specifically choose Sunday and Monday with working hours ranging from 08.00 to 20.00, the output should be 1&08:00&20:00,2&08:00&20:00. How can I achieve this using Vue.js? This is my current code: <script> submitBox = new Vue( ...

Does a single variable contain the number of characters in a stored procedure?

CREATE PROCEDURE Testing1 @Varaible nvarchar(50), @value integer AS BEGIN DECLARE @SUMM FLOAT SET @SUMM=(@value*2.38/7.456)*2 PRINT @Varaible PRINT 'EXPENSES IS' PRINT @SUMM END Output is: PETER EXPENSES IS 24.2597 This piece of code showcases a ...

The world of coding comes alive with Quartz Composer JavaScript

Seeking assistance as I navigate through a challenging project. Any help would be greatly appreciated. Thanks in advance! I have a Quartz Composition where I aim to incorporate a Streetview from Google Maps and control the navigation, but I'm unsure ...

Challenges regarding OAuth2 and the angular-auth2-oidc Library - Utilizing PKCE Code Flow

As a newcomer to OAuth2 and the angular-auth2-oidc library, I may make some beginner mistakes, so please bear with me. MY GOAL: I aim to have a user click on the login link on the home page, be directed to the provider's site to log in, and then retu ...

Determine the number of strings that start with the letter "x" and save them in an

I created a regex in String to store JSON Data, and I was able to identify all images in the JSON Data : Pattern pattern = Pattern.compile("<a[^>]*>"); Matcher matcher = pattern.matcher(contentString.toString()); while(matcher.fi ...

I'm struggling to adjust the height of a div based on whether a list item within it contains a nested unordered

I have been working on a horizontal menu that is functioning well for me. However, according to the design requirements, I need to adjust the height of <div id="nav-subMenu"></div> if the main/parent menu li does not have any submenus or ul. Th ...

Display a linear list organized in a tree format, showcasing instances where children have multiple parents

I am new to Javascript and programming in general. I am working with a list of "step" objects that have a choice/solution field which references another object in the same list. My goal is to create a tree hierarchy based on this field. [ Below is the arr ...

Steps for eliminating a button when the API no longer provides any information

Everything is functioning smoothly with the code below, but I would like to enhance it so that when I call getNextPers() and there is no information available, the Ver Mais button disappears. I have been researching solutions without success, so any assi ...

The React router Link does not update the route after an if statement is executed

I'm in need of some assistance regarding React.js. Despite my efforts to find a solution, nothing has worked for me so far. Here are some examples of what I've searched for: How to use Redirect in the new react-router-dom of Reactjs Redirectin ...

Locating the highest point in an extensive dataset using Python

Is there a method to filter out data points that are far from the peak? For instance, if my dataset contains 10 million points and the peak is approximately at 5 million, how can I remove points that are significantly distant from the peak in order to pin ...

Implementing OutlinePass from Three.js in React

I am attempting to implement the Post-processing Outline Thee.js example in a React environment with server-side rendering. The challenge I am facing revolves around lines 47 and 280 in the example: <script src="js/postprocessing/OutlinePass.js">< ...

Using 'require' within a nested directive that relies on the parent directive in AngularJS

Implementing a sub directive to be utilized in multiple directives is my current challenge. These parent directives share a common controller that has useful methods for updating scope variables within these directives: (potentially changing controllers ...

Request with an HTTP header for authentication

Here's a straightforward question that may seem simple to some developers but could be tricky for beginners. So, my question is - how can I send an HTTP request from a browser when a user clicks a button and also add an authorization header to the re ...

Prevent the dropdown from closing after clicking on a href link

Is there a way to ensure that my dropdown remains open even after a page reload? I'm looking for a solution where clicking on an item(href) within the dropdown will keep it open after redirection. I've tried using the jQuery method called stopPr ...

Tips for including images while drafting an article

In my current project, users are able to write articles. One feature of the editor is the ability to upload photos and include them in the article. While this functionality works well, there is an issue with how the photos are handled and stored. Each ar ...

Getting data from a xhttp.send() request in a Node.js Express server

On my front page, I have this code snippet: var x = "Hi"; var y = 123; xhttp.open("POST", "/toNodeServer", true); xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.send(x, y); Meanwhile, on the server ...

Could the issue at hand possibly stem from the fact that the router isn't fully operational? It appears that router.query

Having trouble retrieving the parameters from the URL using router.query. I've tried various approaches but keep getting an undefined result. It seems like I'm on the right track, though. Highlighted query param in yellow... https://i.stack.img ...

How to retrieve the content/value from a textfield and checkbox using HTML

I'm encountering an issue with my HTML code where I am unable to extract data from the HTML file to TS. My goal is to store all the information and send it to my database. Here is a snippet of the HTML: <h3>Part 1 : General Information</h3 ...

Stop auto-refreshing when a popup is active

As I work on a GSP (Grails) page, there are links that trigger a popup using thickbox (JQuery). Recently, I implemented a simple JavaScript to refresh the page every 5 minutes. However, I encountered an issue whereby the popup closes whenever the page is ...

Making Jquery data tables editable for cells

After spending the last 4 hours tinkering with this, I have hit a wall and can't seem to make any progress. I am attempting to use the jquery datatable featured in this link: http://datatables.net/examples/api/editable.html (a widely used plugin). I h ...