Is there any standard way or algorithm for below transformation of matrix in relative position in the space considering x=0 and y=0
as origin and downward y-axis
and rightward x-axis
as positive axes.
[ [{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}] ]
Now because the length of this array of arrays is 5 and length of longest array within it is 4, I need transformed matrix of size 5 * 4 in below format.
[ [{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}] ]
In the above case there relative positions are preserved.
Thanks in advance!!
Solution reduces out all the unique x values into sorted flat array first.
Then loop over each row of data and go through each row array splicing null
into the holes
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)))