Full-on brain fart mode today. Can’t think of a clean way to do this without an ugly loop/recursion.
I need to take a 2D array of numbers:
const layoutMatrix = [
1,
[1],
[0.5, 0.5],
[0.2, 0.4, 0.4],
];
… and convert this to an array of objects where each entry represents a value from this array where span is the value, and row is the index of each first-level array:
[
{ row: 0, span: 1 },
{ row: 1, span: 1 },
{ row: 2, span: 0.5 },
{ row: 2, span: 0.5 },
{ row: 3, span: 0.2 },
{ row: 3, span: 0.4 },
{ row: 3, span: 0.4 },
]
Prerequisites:
- The array will only ever be 2 levels deep like this, never more. So no need for full-on recursion, I suppose.
- The values for each entry can be either a number or an array of numbers.
>Solution :
flatMap the outer array, mapping the inner arrays to row, span pairs…
const layoutMatrix = [
1,
[1],
[0.5, 0.5],
[0.2, 0.4, 0.4],
];
const objs = layoutMatrix.flatMap((value, row) => {
if (typeof value === 'number') value = [value];
return value.map((span) => ({ row, span }));
});
console.log(objs);