Transform an array into a personalized grid layout

I am currently working on a grid that resembles a table, but is custom-created with divs and spans. My goal is to populate each cell with values from multiple arrays, however, I am encountering some difficulties in making it work properly.

function generate(count, values) {
    return Array.apply(null, { length: count }).map(function () {
        var r = [],
            array = values.slice();
        while (array.length) {
            r.push(array.splice(Math.floor(Math.random() * array.length), 1)[0]);
        }
        return r;
    });
};

var myStringArray = generate(7, [1, 2, 3, 4, 5, 6, 7]);
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
  console.log(myStringArray[i]);
}

Despite my efforts, I have not been able to successfully add each array to its corresponding row.

    Array.from(document.getElementsByClassName('cell')).forEach(function(e, j) {
  e.textContent = myStringArray[i];

});

Check out the fiddle here for more details.

Answer №1

It seems like there may be some confusion, but you can give this JS code a try.

To work with your 2D Array, we first need to calculate the x and y coordinates, which correspond to the index of your cells. If you have 7 cells in a row and 4 rows, you will end up with 28 output elements (referred to as Cell). These Cell's are arranged in a single long 1D array. Each new row starts after every 7th element (and likewise for subsequent rows). The column number is determined by taking the index (number of Cell within the 1D array) modulo 7 (the number of elements in one row).

For example: Index 0 --> x = Index % 7 = 0 % 7 = 0 Index 6 --> x = Index % 7 = 6 % 7 = 6 Index 7 --> x = Index % 7 = 7 % 7 = 0 We also need to find the row number, which is simply the index divided by 7 (the number of elements in one row).

Now that we have the coordinates x and y, we can use them within the 2D Array.

Array.from(document.getElementsByClassName('cell')).forEach(function(e, j){
  //
  var y = Math.floor(j/myStringArray.length);
  var x = j%myStringArray.length;
  e.textContent = myStringArray[y][x] /*+"("+x+","+y+")"*/;
});

Feel free to check out the edited fiddle: https://jsfiddle.net/truvh94a/6/

If this isn't what you were looking for, please provide an example result for further assistance.

Answer №2

Looking at your issue from a fresh perspective with two alternative utility functions, different from your existing generate.

//function that retrieves an Array of nodes matching the css-selector
function $$(selector, ctx){
    if(!ctx || !ctx.querySelectorAll) ctx = document;
    return Array.from(ctx.querySelectorAll(selector));
}

//method to shuffle an Array and return it
function shuffle(arr){
    for(var i=arr.length, j, tmp; i-->1;){
        tmp = arr[ j = 0|(Math.random() * i) ];
        arr[j] = arr[i];
        arr[i] = tmp;
    }
    return arr;
}

//Iterate through all `.row` elements ...
$$('.row').forEach(function(row){
    // ... create a shuffled sequence ...
    var values = shuffle([1,2,3,4,5,6,7]);
    //... and assign these values to the textContent of the `.cell` elements
    $$('.cell', row).forEach(function(cell, i){
        cell.textContent = values[i];
    });
});

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 it possible to obtain a return value from Electron's webContents.executeJavaScript when NodeIntegration is disabled?

Is there a way to retrieve a return value without using NodeIntegration in Electron, similar to ipcRenderer when it's enabled? ...

Optimal management using an image and an onClick event to trigger a JavaScript function

Which control stands out as the optimal choice for displaying images, executing JavaScript functions without postback, and possibly even changing images on hover? ...

"Using Three.js GLTF, switch the material of one object to match the material of

Recently, I encountered an interesting challenge with a scene imported from a glb-file using GLTFLoader. The scene features various objects of guys in different colors, each with its own material (RedMat, BlueMat, GreenMat, etc) created in Blender. Interes ...

Converting an ArrayList<String> to an array<out String> in Kotlin: A step-by-step guide

I am looking for assistance with converting an ArrayList into an Array in Kotlin. Could someone please help me understand how to achieve this? fun createInputData(dataItems : ArrayList<String>) : Data { return Data.Builder() ...

Calculate the total rows within a specified date range

Within my database, there is a column named IsStaff, which returns a value as a bit. This signifies whether a staff member in a company has an illness (1) or not (0). How can I construct an SQL query to count the occurrences of both 1's and 0's w ...

JSON.stringify doesn't support circular structures in Loopback and mongodb, resulting in a TypeError

I have been working on implementing a remote method for loopback and have encountered an issue. "use strict"; module.exports = function(Quote) { /** * * @param {Function(Error, object)} callback */ Quote.random = function(callback) { ...

Convert the PHP datetime and timezone function to a JavaScript function

I have a helpful function in my solution that I'd like to share: public static function formatTime($time, $timezone) { $timezone = new \DateTimeZone($timezone); $time = $time->setTimezone($timezone); return \Locale::getDefaul ...

Error with NEXTJS: Prop type failed - The prop `href` in `<Link>` is expecting a `string` or `object`, but received `undefined`

After importing the Link from next/link and attempting to pass the dynamic endpoint in my components, I encountered an error message. https://i.stack.imgur.com/eqUK8.png https://i.stack.imgur.com/eIC4V.png I searched for a solution and came across a sug ...

How come my reducer isn't changing the state of my store with ImmutableJS?

I have the following code within my reducer: const copy_states = fromJS(state); const i_copy_jobs = copy_states.get('calendar_jobs').get(s_from_day_key).get(s_dept_id).get(s_job_id); let i_calend ...

Ways to retrieve and update the state of a reactjs component

I'm facing an issue with modifying a React JS component attribute using an event handler. export default interface WordInputProps { onWordChange:(word:string) => void firstLetter:string disabled?:boolean } These are the props for my co ...

Remove the final 5 characters from the HTML text

Below is the code block that I am unable to modify: <div class="parent"> <div class="wrap"> <span class="content">2026-01-31-08:00</span> </div> <div class="wrap" ...

Launching the Node.js application on Heroku resulted in encountering an issue: "Application error - There was a problem within the application

When I access the browser using http://localhost:8080/, I can see the message Hello World with Express. I am currently trying to deploy this application on Heroku. I have followed the tutorial provided by Heroku. 1) Create a new app 2) Choose an App name ...

The code in the head section is not running as expected

I've been exploring the possibilities of using lambda on AWS in combination with api gateway to create a contact form for a static S3 website, all inspired by this informative blog post: https://aws.amazon.com/blogs/architecture/create-dynamic-contact ...

MongoDB has encountered an issue where it is unable to create the property '_id' on a string

Currently, I am utilizing Node.js and Express on Heroku with the MongoDB addon. The database connection is functioning correctly as data can be successfully stored, but there seems to be an issue with pushing certain types of data. Below is the database c ...

Is your Material UI Responsive Appbar overlapping the main content? Looking for a solution to address this issue?

Currently, I am in the process of developing a website that incorporates a responsive-based app bar with an attached drawer. The design concept I am following can be located at this link, which I have been modifying to suit my needs. However, I have encoun ...

The AngularJS Factory $http encounters an error when attempting to read the property 'length' of an undefined value

I am looking to implement a factory in my REST Controller that will return an array of Strings. I want to be able to reuse this function in my services.js file. Here is the HTML for an Autocomplete input field: <input type="text" ng-model="vertrag.ver ...

Methods for submitting POST requests with key data enclosed in quotation marks?

Upon investigation, I discovered that the Request Payload object's key does not have quotation marks as shown below. https://i.sstatic.net/U54V9.png However, I am interested in sending a request with keys that are marked with quotations. Interestingl ...

Utilizing Vue JS for filtering numerical data

When I search for letters, my code below works well. However, when it comes to numbers like flat_number, it gives me an error saying flat.flat_number.toLowerCase is not a function filteredList() { return this.Flats.filter((flat) => { return ( ...

Triggering an event through a shared messaging service to update the content of a component

I'm looking for a simple example that will help me understand how I can change the message displayed in my component. I want to trigger a confirmation box with *ngIf and once I confirm the change, I want the original message to be replaced with a new ...

Ways to utilize a single HTML page for various URLs while changing one variable value based on the queried URL

My current HTML page structure looks like this: <body ng-controller="DashboardDisplay" onload="submit()"> <div class="container-fluid" > {{scope.arr}} </div> </body> <script> var myApp = angular.module(&apos ...