Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save filippchistiakov/57390ec98dcaea4502fabc5a32242b3a to your computer and use it in GitHub Desktop.
Save filippchistiakov/57390ec98dcaea4502fabc5a32242b3a to your computer and use it in GitHub Desktop.
UNPIVOT GS
/**
* Unpivot a pivot table of any size.
*
* @param {A1:D30} data The pivot table.
* @param {1} fixColumns Number of columns, after which pivoted values begin. Default 1.
* @param {1} fixRows Number of rows (1 or 2), after which pivoted values begin. Default 1.
* @param {"city"} titlePivot The title of horizontal pivot values. Default "column".
* @param {"distance"[,...]} titleValue The title of pivot table values. Default "value".
* @return The unpivoted table
* @customfunction
*/
function unpivot(data,fixColumns,fixRows,titlePivot,titleValue) {
var fixColumns = fixColumns || 1; // how many columns are fixed
var fixRows = fixRows || 1; // how many rows are fixed
var titlePivot = titlePivot || 'column';
var titleValue = titleValue || 'value';
var ret=[],i,j,row,uniqueCols=1;
// we handle only 2 dimension arrays
if (!Array.isArray(data) || data.length < fixRows || !Array.isArray(data[0]) || data[0].length < fixColumns)
throw new Error('no data');
// we handle max 2 fixed rows
if (fixRows > 2)
throw new Error('max 2 fixed rows are allowed');
// fill empty cells in the first row with value set last in previous columns (for 2 fixed rows)
var tmp = '';
for (j=0;j<data[0].length;j++)
if (data[0][j] != '')
tmp = data[0][j];
else
data[0][j] = tmp;
// for 2 fixed rows calculate unique column number
if (fixRows == 2)
{
uniqueCols = 0;
tmp = {};
for (j=fixColumns;j<data[1].length;j++)
if (typeof tmp[ data[1][j] ] == 'undefined')
{
tmp[ data[1][j] ] = 1;
uniqueCols++;
}
}
// return first row: fix column titles + pivoted values column title + values column title(s)
row = [];
for (j=0;j<fixColumns;j++) row.push(fixRows == 2 ? data[0][j]||data[1][j] : data[0][j]); // for 2 fixed rows we try to find the title in row 1 and row 2
for (j=3;j<arguments.length;j++) row.push(arguments[j]);
ret.push(row);
// processing rows (skipping the fixed columns, then dedicating a new row for each pivoted value)
for (i=fixRows;i<data.length && data[i].length > 0;i++)
{
// skip totally empty or only whitespace containing rows
if (data[i].join('').replace(/\s+/g,'').length == 0 ) continue;
// unpivot the row
row = [];
for (j=0;j<fixColumns && j<data[i].length;j++)
row.push(data[i][j]);
for (j=fixColumns;j<data[i].length;j+=uniqueCols)
ret.push(
row.concat([data[0][j]]) // the first row title value
.concat(data[i].slice(j,j+uniqueCols)) // pivoted values
);
}
return ret;
}
@helmanfrow
Copy link

This is an excellent script. I use it every day. Thank you!

@grimelda
Copy link

grimelda commented Sep 9, 2020

Wow, this is exactly what I have needed all my life. Excellent script, thank you.

@daniel-klaus
Copy link

Really useful. Thank you so much for sharing 🥇

@twhay
Copy link

twhay commented Jan 20, 2021

As much as I love using R or Python to do a quick unpivot, sometimes you just need to do it in Google Sheets. This is a great Google App Script function, thank you for sharing.

@bactisme
Copy link

Hello,

With the two rows of headers setup, the functions was not exactly doing what I wanted.
Here is what I am trying to achieve :

Capture d’écran 2021-02-20 à 11 07 03

In order to do that I modified your version. Here is the forked gist :
https://gist.github.com/bactisme/fbb1fd1c19a9f78e5f15fc7e218a4904

Thanks again.

@helmanfrow
Copy link

By the way, Google Sheets has an undocumented function called FLATTEN() which can be used to unpivot wide data much like this script can. I've used it and it works quite well. Instructions are floating around the web and are not too hard to find.

@SandroMarques1972
Copy link

Thank you for sharing! It was exactly what I needed!

@chinmaykhandalkar
Copy link

I encountered "Too large data" error when I run this script, any ideas how I can get around that?

@BriPoll
Copy link

BriPoll commented Sep 11, 2022

Perfect! Huge help.
Thanks!

@AbyssFolk
Copy link

AbyssFolk commented Jan 9, 2023

If you have csv like

Name, cat 1, cat 2, cat 3, cat 4

and you want to flatten it for look up purpopses

you wil have to UNPIVOT

to do so..

make the data do the following

Name,Name,Name,Name,cat 1, cat 2, cat 3, cat 4

Then Flatten the first 4 columns

and then next to it flatten the next 4 columns,

it should alone

Name,Cat 1
Name, Cat 2
Name, Cat 3,
Name, Cat 4

Right?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment