'Creating One to N rows [duplicate]

I am struggling with creating a script that takes each value from col A and maps them based on values in col C and D.

Image below for visual explanation:

Snapshot of Data and Output



Solution 1:[1]

I believe what you are trying to find is the Cartesian Product of columns A, C, and D.

Here I implemented rsp answer on Cartesian product of multiple arrays in JavaScript to your issue.

Try this:

Code:

function myFunction() {
  var sh = SpreadsheetApp.getActiveSheet();
  var nameRangeLastRow = sh.getRange("A1").getNextDataCell(SpreadsheetApp.Direction.DOWN).getLastRow();
  var nameVal = sh.getRange(2, 1, nameRangeLastRow - 1, 1).getValues().flat();
  var regionRangeLastRow = sh.getRange("C1").getNextDataCell(SpreadsheetApp.Direction.DOWN).getLastRow();
  var regionVal = sh.getRange(2, 3, regionRangeLastRow - 1, 1).getValues().flat();
  var positionRangeLastRow = sh.getRange("D1").getNextDataCell(SpreadsheetApp.Direction.DOWN).getLastRow();
  var positionVal = sh.getRange(2, 4, positionRangeLastRow - 1, 1).getValues().flat();
  const cartesian = (...a) => a.reduce((a, b) => a.flatMap(d => b.map(e => [d, e].flat())));
  var result = cartesian(nameVal, regionVal, positionVal);
  sh.getRange(2, 6, result.length, 3).setValues(result);
}

Output:

enter image description here enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nikko J.