I believe your goal as follows.
You want to achieve the following conversion using Google Apps Script.
From
Blue 74 Shirt
Red 48 Pants
Green 55 Shoes
Hat
Socks
Backpack
To
Blue 74 Shirt
Blue 74 Pants
Blue 74 Shoes
Blue 74 Hat
Blue 74 Socks
Blue 74 Backpack
Red 48 Shirt
Red 48 Pants
Red 48 Shoes
Red 48 Hat
Red 48 Socks
Red 48 Backpack
Green 55 Shirt
Green 55 Pants
Green 55 Shoes
Green 55 Hat
Green 55 Socks
Green 55 Backpack
In your sample Spreadsheet, Green, 55
has all the same value which is Backpack
. But from your sample pattern, I thought that you might have wanted the avove conversion.
If my understanding is correct, I would like to propose the following flow.
- Retrieve the values from the columns "A" to "C".
- Transpose the retrieved values.
- Create the array for putting to Spreadsheet.
- Put the values.
When above flow is reflected to the script, it becomes as follows.
Sample script:
Please copy and paste the following script to the script editor of the Spreadsheet, and run myFunction
. By this, the result values are put to the columns "I2:K".
function myFunction() {
const sheetName = "Sheet1"; // Please set the sheet name.
// 1. Retrieve the values from the columns "A" to "C".
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
const values = sheet.getRange("A2:C" + sheet.getLastRow()).getValues();
// 2. Transpose the retrieved values.
const [color, id, item] = values[0].map((_, i) => values.map(r => r[i]).filter(String));
// 3. Create the array for putting to Spreadsheet.
const res = color.flatMap((e, i) => item.map(g => [e, id[i], g]));
// 4. Put the values.
sheet.getRange(2, 9, res.length, res[0].length).setValues(res);
}
Result:
When above script is run for your sample Spreadsheet, the following result is obtained.

References: