Skip to content

Instantly share code, notes, and snippets.

@scmmishra
Last active December 12, 2019 10:45
Show Gist options
  • Save scmmishra/687df46443e6abda5a1aea6b5eaab228 to your computer and use it in GitHub Desktop.
Save scmmishra/687df46443e6abda5a1aea6b5eaab228 to your computer and use it in GitHub Desktop.
Generate CSS grid template area using JS
function add(a, b) {
return a + b;
}
const data = [
{
name: 'A',
columns: 3,
rows: 3
},
{
name: 'B',
columns: 3,
rows: 2
},
{
name: 'C',
columns: 1,
rows: 3
},
{
name: 'D',
columns: 2,
rows: 2
},
{
name: 'E',
columns: 3,
rows: 3
}
]
// Split the data into multiple arrays
// Each array will contain grid elements of one row
processed = []
temp = []
let init = 0
data.forEach((data) => {
init = init + data.columns;
if (init > 6) {
init = data.columns
processed.push(temp)
temp = []
}
temp.push(data)
})
processed.push(temp)
grid_template = [];
processed.forEach(data => {
let max = Math.max.apply(null, data.map(a => a.columns));
for (let cur_idx = 0; cur_idx < max; cur_idx++) {
aa = data.map(dd => {
if (dd.rows > cur_idx) {
return Array.apply(null, Array(dd.columns)).map(String.prototype.valueOf, dd.name).join(" ")
}
}).join(" ")
grid_template.push(aa)
}
})
console.log(grid_template)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment