From your provided sample expected value, I believed your goal is as follows.
From your showing table (Spreadsheet), you want to retrieve the following value using Google Apps Script.
{
"R1":["S1","S2"],
"R2":["S1","S2","S3"],
"R3":["S1","S2","S3"]
}
In this case, how about the following sample script?
Sample script:
function myFunction() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
const values = sheet.getRange("A2:B" + sheet.getLastRow()).getValues();
const res = values.reduce((o, [a, b]) => (o[a] = o[a] ? [...o[a], b] : [b], o), {});
console.log(res)
}
- When this script is run,
res
is {"R1":["S1","S2"],"R2":["S1","S2","S3"],"R3":["S1","S2","S3"]}
.
Testing:
From your showing table, values
is [["R1","S1"],["R1","S2"],["R2","S1"],["R2","S2"],["R2","S3"],["R3","S1"],["R3","S2"],["R3","S3"]]
. When this value is used, the test script is as follows.
const values = [["R1","S1"],["R1","S2"],["R2","S1"],["R2","S2"],["R2","S3"],["R3","S1"],["R3","S2"],["R3","S3"]]
const res = values.reduce((o, [a, b]) => (o[a] = o[a] ? [...o[a], b] : [b], o), {});
console.log(res)
Note:
In your expected value, you show as follows. But, I thought that from your showing table, R2
of 2nd R2: [S1,S2,S3]
might be R3
.
{
R1: [S1,S2],
R2: [S1,S2,S3],
R2: [S1,S2,S3]
Reference: