unpivotColumns(rows, {keepCols, nameHeader, valueHeader}) turns a wide 2D array into long rows. The first row is headers. Columns you name in keepCols are copied onto every output row; each remaining header becomes a name/value pair. Blank values are skipped unless you pass keepBlanks: true. The input array is not modified.
When to use
- A month-by-month (or quarter-by-quarter) table that you want to feed to a pivot table
- Keeping identifier columns (item, region) and stacking the period columns underneath them
- Writing the long table to a new tab so the wide original stays put
How to use this snippet
keepCols can be 0-based indexes or header names. If you omit it, the first column is kept. nameHeader and valueHeader default to name and value. Zero is a value, not a blank; empty strings and whitespace-only cells are blanks.
/**
* Unpivot a wide 2D array (first row = headers) into long rows.
* keepCols are 0-based indexes or header names and default to [0].
* nameHeader and valueHeader default to "name" and "value".
* Blank value cells are skipped unless opts.keepBlanks is true.
* Does not mutate the input. Throws if a keepCols header or index
* is missing.
*
* @param {Array<Array<*>>} rows
* @param {{keepCols?: Array<number|string>, nameHeader?: string, valueHeader?: string, keepBlanks?: boolean}} [opts]
* @return {Array<Array<*>>}
*/
function unpivotColumns(rows, opts) {
opts = opts || {};
var src = rows && rows.length ? rows : [];
var nameHeader =
opts.nameHeader == null || String(opts.nameHeader).trim() === ''
? 'name'
: String(opts.nameHeader);
var valueHeader =
opts.valueHeader == null || String(opts.valueHeader).trim() === ''
? 'value'
: String(opts.valueHeader);
var keepBlanks = opts.keepBlanks === true;
var header = src.length ? src[0] : [];
var width = header.length;
var keep = resolveKeepCols_(opts.keepCols, header, width);
var outHeader = [];
var i;
for (i = 0; i < keep.length; i++) outHeader.push(header[keep[i]]);
outHeader.push(nameHeader, valueHeader);
var out = [outHeader];
var keepSet = {};
for (i = 0; i < keep.length; i++) keepSet[keep[i]] = true;
var r, c, row, value, isBlank, outRow;
for (r = 1; r < src.length; r++) {
row = src[r] || [];
for (c = 0; c < width; c++) {
if (keepSet[c]) continue;
value = c < row.length ? row[c] : '';
isBlank =
value == null ||
value === '' ||
(typeof value === 'string' && String(value).trim() === '');
if (isBlank && !keepBlanks) continue;
outRow = [];
for (i = 0; i < keep.length; i++) {
outRow.push(keep[i] < row.length ? row[keep[i]] : '');
}
outRow.push(header[c], isBlank ? '' : value);
out.push(outRow);
}
}
return out;
}
function resolveKeepCols_(keepCols, header, width) {
var i, v, idx, name, found;
var cols = keepCols;
if (cols == null) cols = [0];
if (Object.prototype.toString.call(cols) !== '[object Array]') cols = [cols];
var out = [];
var seen = {};
for (i = 0; i < cols.length; i++) {
v = cols[i];
if (typeof v === 'number' && isFinite(v)) {
idx = Math.floor(v);
if (idx < 0 || idx >= width) {
throw new Error('unpivotColumns: keepCols index out of range: ' + v);
}
} else {
name = String(v == null ? '' : v).trim();
found = -1;
for (idx = 0; idx < width; idx++) {
if (String(header[idx] == null ? '' : header[idx]).trim() === name) {
found = idx;
break;
}
}
if (found < 0) {
throw new Error('unpivotColumns: keepCols header not found: ' + name);
}
idx = found;
}
if (seen[idx]) continue;
seen[idx] = true;
out.push(idx);
}
if (!out.length) {
throw new Error('unpivotColumns: keepCols cannot be empty');
}
return out;
}
Example
function writeLongMonthTable() {
var ss = SpreadsheetApp.getActive();
var src = ss.getSheetByName('Wide');
var data = src.getDataRange().getValues();
var longRows = unpivotColumns(data, {
keepCols: ['Item'],
nameHeader: 'Month',
valueHeader: 'Value'
});
var dest = ss.getSheetByName('Long');
if (!dest) dest = ss.insertSheet('Long');
dest.clearContents();
dest.getRange(1, 1, longRows.length, longRows[0].length).setValues(longRows);
}
If you also want to keep a Region column, pass keepCols: ['Item', 'Region']. Then build the pivot table on the Long tab, not on Wide.
Notes
clearContentson the destination tab drops values and leaves formatting. It does not touch the source sheet.- Header names in
keepColsmust match the first row exactly, after trim. Unknown names or out-of-range indexes throw. - This helper only reshapes arrays. It does not create a Sheets pivot table for you.
Happy Coding!
