Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flatten 2D array of numbers into array of objects with “row” index?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
  { 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:

  1. The array will only ever be 2 levels deep like this, never more. So no need for full-on recursion, I suppose.
  2. 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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading