Skip to content

Instantly share code, notes, and snippets.

@ndthanh

ndthanh/unpivot.gs

Created May 11, 2020
Embed
What would you like to do?
/**
* Unpivots the given data
* More: https://stackoverflow.com/questions/24954722/how-do-you-create-a-reverse-pivot-in-google-sheets
*
* @return Unpivoted data from array
* @param {object[][]} arr 2D Input Array
* @param {object[][]=} headers [optional] Custom headers for output
* @customfunction
*/
function unpivot(arr, headers) {
const custHeader = arr.shift();
custHeader.shift();
const out = arr.flatMap(([sale, ...qty]) =>
qty.map((num, i) => [custHeader[i], sale, num])
);
if (headers) out.unshift(headers[0]);
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment