在坐标的相对位置显示矩阵的算法

Algorithm to display matrix in relative position of coordinates

考虑x=0 and y=0为原点,向下y-axis和向右x-axis,在space中是否有任何标准的方法或算法对矩阵相对位置进行以下变换正轴。

[ [{x:36,y:14},{x:242,y:14}],
  [{x:36,y:133}],
  [{x:36,y:252}],
  [{x:36,y:371},{x:242,y:371},{x:446,y:371},{x:651,y:371}],
  [{x:242,y:490},{x:446,y:490},{x:651,y:490}] ]

现在因为这个数组的长度是5,其中最长的数组的长度是4,我需要变换矩阵大小为 5 * 4,格式如下。

[ [{x:36,y:14},{x:242,y:14},null,null],
  [{x:36,y:133},null,null,null],
  [{x:36,y:252},null,null,null],
  [{x:36,y:371},{x:242,y:371},{x:446,y:371},{x:651,y:371}],
  [null,{x:242,y:490},{x:446,y:490},{x:651,y:490}] ]

在上面的例子中,相对位置被保留了。

提前致谢!!

检查这段代码。解释将在那里评论。

function normalize(array){

 // Get the largest sub-array. We will save this as a reference
 // to use it later
 var longest_value = array.reduce((a,b)=>a>b?a:b)


 // map each element in the main array
 return array.map(function(a){ 

  // for each item return a modified copy of the largest one.
  // To do this we map it
  return longest_value.map(function(b,i){

   // we the item with the same x position in the current main array item
   var v = a.filter(r=>r.x==b.x)

   //if there is, we return it, is not we return null
   return v.length? v[0] : null
  })
 })
}


console.log(normalize([ [{x:36,y:14},{x:242,y:214}],[{x:36,y:133}],[{x:36,y:252}],[{x:36,y:371},{x:242,y:371},{x:446,y:371},{x:651,y:371}],[{x:242,y:490},{x:446,y:490},{x:651,y:490}] ]))

解决方案首先将所有唯一的 x 值减少到排序的平面数组中。

然后遍历每一行数据,遍历每一行数组拼接null进入空洞

let data =[ [{x:36,y:14},{x:242,y:214}],
  [{x:36,y:133}],
  [{x:36,y:252}],
  [{x:36,y:371},{x:242,y:371},{x:446,y:371},{x:651,y:371}],
  [{x:242,y:490},{x:446,y:490},{x:651,y:490}] ]
  
  
let xVals  = [...new Set(data.reduce((a,c)=>a.concat(c.map(({x})=>x)),[]))].sort((a,b)=>a-b)

data.forEach(row=>{
   xVals.forEach((x,i)=>{
      if(row[i] === undefined  || row[i].x > x){
          row.splice(i,0, null)
      }
   });
});

 data.forEach(arr=>console.log(JSON.stringify(arr)))