How to unpivot a table using Google Apps Script?

旧巷老猫 提交于 2020-03-23 12:03:04

问题


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);
    }
  }
}

回答1:


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());


来源:https://stackoverflow.com/questions/60530277/how-to-unpivot-a-table-using-google-apps-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!