JSFiddle - React, Tailwind, and code Playground

Setting grid layout for Flat array.

by Arvind Pal

JavaScript

let insights = [
	{ "id": 1, grid: 6 },
  { "id": 2, grid: 7 },
  { "id": 3, grid: 3 },
  { "id": 4, grid: 2 },
  { "id": 5 },
  { "id": 6, grid: 2 },
  { "id": 7, grid: 6 },
];

let x = 0, y = 0, h = 3, w = 0;

let layout = [];
  
insights.forEach(insight => {

	let grid = 12;
  
  if (insight.grid !== undefined) grid = insight.grid;
  
  if ((w + grid) > 12) {
  	x = 0;
    w = 0;
    y += 3;
  }
  
  let toPush = { i: insight.id, x, y, w: grid, h };
  
  console.log("\ninsight ==> ", insight);
  console.log("layout ==> ", toPush);
  
  layout.push(toPush);
  
  x += grid;
  w += grid;
});

console.log("\n\n[Final] insights ==> ", JSON.stringify(insights, null, 2));
console.log("[Final] layout ==> ", JSON.stringify(layout, null, 2));