How to unpivot a table using Google Apps Script?

Gustavo Rita :

I have a table in a spreadsheet which I want to unpivot using google apps script: each one of the month rows of the original table have to become multiple rows in the new table. The problem is the code doesn't produce the expected result.

Insted of creating arrays that ends like this (each line of the table ends with one different month):

[[...,'April'],[...,'September'],[...,'December']]

It's producing this (each line ends with the last month value of that line in the original table):

[[...,'December'],[...,'December'],[...,'December']]

Can someone see the mistake?

function myFunction() {
  var ay_datos = [
    ['State', 'Month1', 'Month2', 'Month3', 'Number of months', 'Month'],
    ['California', 'April', 'September', 'December', 3, ''],
    ['Texas', 'January', 'March', '', 2, ''],
  ];
  var ay_new = [
    ['State', 'Month1', 'Month2', 'Month3', 'Number of months', 'Month'],
  ];

  for (i = 1; i < ay_datos.length; i++) {
    var num_months = ay_datos[i][4];
    var ay_linea = ay_datos[i];

    for (j = 0; j < num_months; j++) {
      ay_linea[5] = ay_linea[1 + j];
      ay_new.push(ay_linea);
    }
  }
}
TheMaster :

You're pushing the same array each time in a loop. Any modifications done to the array will reflect on all references of the same array. Use slice to copy a array:

  ay_linea[5] = ay_linea[1 + j];
  ay_new.push(ay_linea.slice(0));

Live snippet:

function myFunction() {
  const ay_datos = [
    ['State', 'Month1', 'Month2', 'Month3', 'Number of months', 'Month'],
    ['California', 'April', 'September', 'December', 3, ''],
    ['Texas', 'January', 'March', '', 2, ''],
  ];
  const ay_new = [
    ['State', 'Month1', 'Month2', 'Month3', 'Number of months', 'Month'],
  ];

  for (let i = 1; i < ay_datos.length; i++) {
    const num_months = ay_datos[i][4];
    const ay_linea = ay_datos[i];

    for (let j = 0; j < num_months; j++) {
      ay_linea[5] = ay_linea[1 + j];
      ay_new.push(ay_linea.slice(0));
    }
  }
  return ay_new;
}
console.log(myFunction());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29883&siteId=1