Johannes Müller Johannes Müller - 7 months ago 25
HTML Question

Connect Rectangles that are adjacent?

I want to connect Rectangle-Objects in Array, which are side by side (adjacent). For example:(Structure: "{x: x-Postion, y: y-Postion, x1: width, y1: height}")

{x: 0, y: 0, x1: 3, y1: 2}, {x: 0, y: 2, x1: 3, y1: 2}


can put together (as I want it) to:

{x: 0, y: 0, x1: 3, y1: 4}


Till now I couldn't find a solution for my problem, so that I hope you can help me. This a part of my array, where I want to find these side by side - Rectangles and save them in a new Array:

[{x:0, y: 0, x1:3, y1:2},{x:0, y: 2, x1:3, y1:2},{x:0, y: 4, x1:3, y1:2},{x:0, y: 6, x1:3, y1:2},{x:0, y: 8, x1:3, y1:2},{x:0, y: 10, x1:3, y1:2},{x:0, y: 12, x1:3, y1:2},{x:0, y: 14, x1:3, y1:2},{x:0, y: 16, x1:3, y1:2},{x:0, y: 18, x1:3, y1:2},{x:0, y: 20, x1:3, y1:2},{x:0, y: 22, x1:3, y1:2},{x:0, y: 24, x1:3, y1:2},{x:0, y: 26, x1:3, y1:2},{x:0, y: 28, x1:3, y1:2},{x:0, y: 30, x1:3, y1:2}//[...]so on

Answer

This should do it. At the beginning i couldn't recognize that the rectangles were stacked on top of each other. I had to think for all conditions. I believe it recursively searches and merges wherever the rectangles are placed, if their touching edges are same in size.

var   rects = [{x:0, y: 0, x1:3, y1:2},{x:0, y: 2, x1:3, y1:2},{x:0, y: 4, x1:3, y1:2},{x:0, y: 6, x1:3, y1:2},{x:0, y: 8, x1:3, y1:2},{x:0, y: 10, x1:3, y1:2},{x:0, y: 12, x1:3, y1:2},{x:0, y: 14, x1:3, y1:2},{x:0, y: 16, x1:3, y1:2},{x:0, y: 18, x1:3, y1:2},{x:0, y: 20, x1:3, y1:2},{x:0, y: 22, x1:3, y1:2},{x:0, y: 24, x1:3, y1:2},{x:0, y: 26, x1:3, y1:2},{x:0, y: 28, x1:3, y1:2},{x:0, y: 30, x1:3, y1:2}];

function rectsReduce(arr){

  function mergeRects(r,sa,a,i){
  	
    function compare(r1,r2){
      return r1.y == r2.y ? r1.x >  r2.x ? r1.x - r2.x == r2.x1
                                         : r2.x - r1.x == r1.x1
                          : r1.x == r2.x ? r1.y > r2.y ? r1.y - r2.y == r2.y1
                                                       : r2.y - r1.y == r1.y1
                                         : false;
    }
  	
    var r2 = a.splice(sa.findIndex(e => compare(r,e))+i+1,1)[0];
    return !!r2 && {x  : Math.min(r.x, r2.x),
                    y  : Math.min(r.y, r2.y),
                    x1 : r.x == r2.x ? r.x1 : r.x1 + r2.x1,
                    y1 : r.y == r2.y ? r.y1 : r.y1 + r2.y1};
  }
	
  return arr.reduce((p,c,i,a) => { var mergedRect = [];
                                   if (a.length > 1) {
                                       mergedRect = mergeRects(c,p.slice(i+1),a,i);
                                       if (!!mergedRect) {
                                           p[i] = mergedRect;
                                           p = rectsReduce(p);
                                       }
                                   }
                                   return p},arr);	
}
document.write("<pre>" + JSON.stringify(rectsReduce(rects)) + "</pre>");