What are the steps to convert a two-dimensional grid into a hierarchical grid structure?

I am interested in converting a flat grid, represented as an array of items with coordinates and sizes, into a hierarchical grid structure where the children are organized into rows and columns.

UPDATE: I initially referred to the flat grid as a "matrix," which may have caused confusion. The main goal is to transition from a flat grid to a tree-like structure. It is possible to convert a matrix into a flat array, like the one I am using here, and then transform it into a tree.

Given a flat grid like this:

var grid = [
    {x:0,y:1,w:1,h:3,id:'f'},
    {x:0,y:0,w:9,h:1,id:'e'},
    {x:1,y:1,w:4,h:2,id:'a'},
    {x:5,y:1,w:2,h:1,id:'b'},
    {x:5,y:2,w:2,h:1,id:'c'},
   ...
];

The desired result would be:

var grid = [
  {
    "w": 9,
    "h": 4,
    "children": [
      {
        "x": 0,
        "y": 0,
        "w": 9,
        "h": 1,
        "id": "e"
      },
      {
        "w": 9,
        ...
    ],
    "x": 0,
    "y": 0
  }
]

Answer №1

Facing a challenge, I took it upon myself to find a solution.

Recognizing that the initial question was unclear, I made adjustments to improve its accuracy.

The process of converting a flat grid into a nested grid involves the following steps:

  • Iterate through all child elements.
  • Examine neighboring elements in all directions to identify adjacencies.
  • Create new groups comprising the item and its adjacent neighbors.
  • Recalculate the size of each group.
  • Repeat until only one child element remains.

I have shared my module on Github: https://github.com/jide/GridPack

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

Concatenate the values from the string variable into an array in JavaScript

As the heading suggests, I am facing an issue with setting an array from a string variable. /*** ATTEMPT THAT FAILED ***/ var Multi = []; var test = "[0,1],[1,5],[2,3],[3,10]"; Multi.push(test); /*** SUCCESSFUL SOLUTION ***/ var Multi = []; Multi.push([ ...

Code-behind not functioning properly for Bootstrap Modal

Whenever the password or username are incorrect, I need to open a modal and keep it in the 'Else' statement. However, it is not working, the modal does not open. protected void bntLogar_Click(object sender, EventArgs e) { Registrar c ...

Retrieve information from two observables without the need for separate subscriptions

After my first observable emits user data from Firebase, I need to make a second call to retrieve additional user information from a different collection. While I can handle these operations separately, the second call should only be triggered once the fir ...

Ensuring Consistency in Object Size When Switching Between Perspective and Orthographic Cameras

Struggling to toggle between Perspective and Orthographic cameras in my script. I need objects at certain depths to maintain their projection size. I've reached a point of confusion when trying to understand the geometry... Can anyone recommend a sim ...

Add unique styles to a jQuery-included HTML document

I'm attempting to use jQuery to load an HTML page into the main body of another page. Specifically, I have a div called sidebar_menu positioned in the middle of the page, and I am loading content at the bottom using jQuery. $("#sidebar_menu").load(" ...

What is the best way to convert into an array of NSObjects?

As someone with a background in Java, I find myself facing an issue when writing the following code: NSObject* obj[] = (NSObject* []) [self getResult]; The error message from the compiler reads Cast to incomplete type 'NSObject *[]' I am wonde ...

When the page is reloaded, the props become null in React Router

I have a primary component named Body with the following structure class Body extends React.Component { state = {}; _redirect = data => { this.setState( { user: data }, () => this.props.history.push("/user_details ...

The swiper slider loop malfunctions when the number of slides is less than the double-value

When using **6 slides** with slidesPerView: 3, everything works fine. However, if I use 5 slides and set slidesPerView: 3, the loop stops after the last slide. var swiper = new Swiper('.swiper-container', { direction: 'ver ...

I am unable to organize an array

I stumbled upon a discussion about clearing an array in JavaScript, but unfortunately I can't participate there. So, here's my query: I have the following code snippet: sumarray.length=0; sumarray = []; for (var i=0; i<3; i++) sumar ...

Conceal the sidebar menu by clicking anywhere outside of the menu bar or the designated button

I attempted to create a menu similar to the semantic UI, but so far I have only been able to click the menu button to open and close the menu. I am using a toggle class to display the sidebar, but I'm unsure if this approach is entirely correct: < ...

Unlocking the potential of NextAuth.js by enhancing the user session with additional database information on authentication

Currently, I am in the process of creating a straightforward credentials sign flow using next-auth ^4.24.5 with a nextjs 14 app. Within my user model, there is a boolean property named 'isAdmin' that I wish to make accessible in my session using ...

Choose the data attribute value and incorporate it into the select dropdown options

I'm brand new to Vue.js. Specifically, the requirement is that the backend will input time slot values into the data-times attributes in array format. My task is to extract and update these time slots based on the selected location. If "Location 1" ...

Experiencing a problem with the localhost connection

I've been trying to work on this issue using React and local host, but it keeps showing the direct file instead of the website. I've been stuck on this problem for the past 3-4 hours and still haven't been able to find a solution. I'm h ...

Sending an array of data using Angular in a web service

Here is my model object from model.ts name_id: string[]; public generateUrlencodedParameters(token: string, id?: number): string { let urlSearchParams = new URLSearchParams(); urlSearchParams.append('name_id', this.name_id.toS ...

What could be causing my jQuery to not function on a separate domain?

Two of my websites have the same code, but one is functioning correctly while the other seems to be having trouble with the jQuery functions <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html;char ...

Struggling to implement CSS for second div onto selected item in the first div

As a beginner in Angular, I am seeking some guidance and examples. In my code, there are two divs. One is created using ng-repeat with an ng-click function to detect the clicked item. The other div below has CSS properties like style="width:100px; float ...

Implementing user profile picture display in express.js: A step-by-step guide

I'm having trouble displaying the profile picture uploaded by users or employees in my application. Although the picture uploads successfully, it doesn't show up and gives an error when I try to redirect to the page. Cannot read property &ap ...

Using the Fetch API to send PUT requests in React.js

My GET routes are functioning properly, however, I am encountering an issue with passing data to my PUT route. The method "saveOverTemplate" in the first file is designed to take the content from my component and send it to the PUT route for updating the d ...

The ng-model-options in Angular 2 is set to "updateOn: 'change blur'"

Currently working with angular 2, I am seeking a solution to modify the behavior of ngModel upon Enter key press. In angular 1.X, we utilized ng-model-options="{updateOn: 'change blur'}". How can this be achieved in angular 2? For reference, her ...

Enhance the functionality of Javascript by integrating the output from a Python script

Integrating Python Script Results into Javascript Code. I am looking to update my Javascript script with the output from a Python script in the context of a Flask application. Currently, I receive a value from my Python script and I want to pass it to or ...