Generate various 2-dimensional arrays of objects in JavaScript, with each object sharing identical properties

Is there a way to efficiently create two 2-D arrays, where each element of the array is an object with unique properties? These arrays are of different sizes and each cell has different properties.

var gridcell = [];
var regionalcell = [];

I have managed to create these arrays using the code below, but I feel that it could be more efficient. Any help would be greatly appreciated!

The values of "w, h, r, c" vary in both functions.

function createCellArray(w, h,r,c) 
{
     for (j = 0; j < r; j++) 
     {
         gridcell[j] = [];
       for (i = 0; i < c; i++) 
       {
         gridcell[j][i] = 
            {
                 "x1": w * i,
                 "y1": h * j,
                 "x2": w * (i + 1),
                 "cell_color": null,
                 "y2": h * (j + 1),
                 "name": (i + 1 * (j * 10)) + 1
            }
        }
     }
}


function createRegionalCellArray(w, h, r, c) {
    for (j = 0; j < r; j++) {
        regional[j] = [];
        for (i = 0; i < c; i++) {
            regional[j][i] =
            {
                "x1": w * i,
                "y1": h * j,
                "x2": w * (i + 1),
                "cell_color": null,
                "y2": h * (j + 1),
                "name": (i + 1 * (j * 10)) + 1
            }
        }
    }
}

Answer №1

It seems like you might be looking for a way to optimize your code... Are you trying to streamline your code?

If that's the case, you can create a function that generates your shared array:

function generateCellArray(width, height, rows, columns) 
{
     var cellArray = [];
     for (row = 0; row < rows; row++) 
     {
       cellArray[row] = [];
       for (col = 0; col < columns; col++) 
       {
         cellArray[row][col] = 
            {
                 "x1": width * col,
                 "y1": height * row,
                 "x2": width * (col + 1),
                 "cell_color": null,
                 "y2": height * (row + 1),
                 "name": (col + 1 * (row * 10)) + 1
            }
        }
     }

     return cellArray;
}

gridCells = generateCellArray(w1, h1, r1, c1);
regionalCells = generateCellArray(w2, h2, r2, c2);

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

Alter Express routes automatically upon updating the CMS

Currently, I am working on a project that utilizes NextJS with Express for server-side routing. lib/routes/getPages const routes = require('next-routes')(); const getEntries = require('../helpers/getEntries'); module.exports = async ...

Troubleshooting: React is not defined in Rollup + React 17 with updated JSX Transform

I'm currently working on prototyping a microfrontend architecture using Rollup and multiple create-react-app applications. However, when I try to locally yarn link my external app with the container app, I am encountering the following error: The err ...

Utilizing PHP to iterate over a JSON array and generate HTML content

I am utilizing bootstrap datatables to present data retrieved from an API in a tabular format. Below is the sample data: { "response_status": { "status_code": 0, "status_message": [ { "reg_number": "123", "company": "Compan ...

Preserve the chosen option in a dropdown menu even after a postback using JavaScript

Seeking Help in Retaining Dropdownlist Selected Value After Postback In my efforts to retain a dropdownlist selected value after postback, I have been exploring various methods. I extract the selected values from the dropdownlist and store them in local ...

Utilizing Express JS to Optimize JPEG File Loading with Cache Headers

I have been working on implementing Cache-Control for my static image files. I have successfully set this header for HTML and JS files: https://i.stack.imgur.com/9VuWl.png However, I am facing challenges with JPEG files: https://i.stack.imgur.com/p52jm. ...

What is the process for implementing a version folder for my @types/definition?

Is there a way to access the typings for react-router in my project? My package.json file currently has this dependency: { "@types/react-router": "^4.0.3" } However, it seems to be using the standard index.d.ts file from DefinitelyTyped library which i ...

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 ...

The outcome of the AJAX RSS Reader remains unpredictable

Utilizing the AJAX RSS Reader (visit this link) for extracting RSS data from my URL: http://vtv.vn/trong-nuoc.rss In my php file (readRSS.php): <?php $url = ("http://vtv.vn/trong-nuoc.rss"); $xmlDoc = new DOMDocument(); $xmlDoc->load($url); $ ...

Keeping an HTML field constantly refreshed with dynamic content from Django

Imagine having two input fields along with an HTML paragraph displaying a Django value. Field A: <input ...> Field B: <input ...> <p>{{ sum }}</p> The goal is to have the sum update in real time, meaning that once both numbers ...

Losing values due to custom $validator and getterSetter in AngularJS / UI Bootstrap

My objective is to create a UI Bootstrap datepicker with an input mask feature. The datepicker directive only validates dates selected using the popup window and not dates manually typed in by the user. To address this, I researched how to implement custo ...

Is there a restriction on the number of strings allowed in minimist?

Here is the output received from the code provided below. Question input and i are both true as intended, but why aren't project and p? They are defined in exactly the same way as input and i. $ bin/test --input -p { _: [], update: fa ...

In the Firebug console, Ajax posts are highlighted in a vibrant red color

Upon executing the code provided, the Firebug was enabled. While submitting the form, in the console, the message "post to login_submit.php" appeared in red. However, there was no response received as well. <!DOCTYPE html> <html> ...

What is the best way to add JSON data into a table on a WordPress site?

I'm working on a WordPress custom page that generates JSON data. I would like to know how I can insert this data into a custom table within the WordPress database. Can someone please guide me on how to achieve this? {"schedule":[{"day":"2017-10-25" ...

Securing client-side code with AngularJS for enhanced security

It's a known fact that once browsers have downloaded frontend files, there's no way to hide code from the client. However, I've heard that clients can debug JavaScript code, add breakpoints, skip code lines (especially security checks), and ...

State not visible in Redux Devtool extension on Chrome browser

I am still getting acquainted with Redux, especially the Redux DevTools. Recently, I developed a simple application where users can be clicked on to display their information. Essentially, the state contains the currently selected user. However, for som ...

Experiencing an issue with Firestore returning null instead of data in JavaScript

I have created a form that, upon submission, adds a document with the data to my Firestore database. Additionally, I have set up a real-time listener on the collection where the document is added. onSubmit={async(e) => { e.preven ...

Building a React component that's a table containing rows that can be scrolled and elements that are clickable

Imagine having a set of events and their respective participants: const myData = { "event_1": ["1", "2","3"], "event_2": ["11", "5","8", "9"], "event_3&quo ...

Creating dynamic routes in react-router-dom using conditions

I'm currently developing an application using react-router-dom for navigation. I've encapsulated all my <Routes> inside a container provided by Material UI. However, I want my home page to be outside of this container so that I can display ...

Intersecting objects with Raycaster in three.js

I'm currently working on customizing this particular example from three.js to enable character control via mouse clicks. My objective is to obtain the mouse coordinates upon clicking the canvas and then convert them into 3D space coordinates using THR ...

Synchronously executing Twitter posts

Hello there! I've been using this code found here to embed Twitter posts on my website. It's been working perfectly on certain pages, like in the forums, but I've run into an issue while browsing through user profiles. The post history for e ...