javascript - 给定两个数组,我如何遍历一个数组并插入第二个数组的重复元素?

标签 javascript arrays google-apps-script unpivot

我正在编写一个 google apps 脚本来获取包含行的工作表:

StudentName, StudentID, Gender, CoursePreference1, CoursePreference2, CoursePreference 3

和输出:

StudentName, StudentID, Gender, CoursePreference1
StudentName, StudentID, Gender, CoursePreference2
StudentName, StudentID, Gender, CoursePreference3

我正在转换格式,不再让每个学生在一行中为他们的每个偏好设置一列,而是为每个类(class)偏好设置一行,并包含重复的学生信息。

我曾尝试使用其他带有嵌套 for 循环和 map 方法的答案来到达我要去的地方,但我完全陷入了困境。

我设置两个数组的代码的前半部分工作正常; studentInfo 的每个元素都旨在为 courseInfo 的关联索引的每个元素重复:

function requestFileConversion() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var input = ss.getSheetByName('Input');
  var output = ss.getSheetByName("Output");

  output.getRange('A2:I').clearContent();
  output.getRange('A2:I').setNumberFormat('@STRING@');

  var studentInfo = input.getRange(2, 1, input.getLastRow() - 1, 8).getValues();
  var courseInfo = input.getRange(2, 9, input.getLastRow() - 1, 23).getValues();

  var appendValues = [];

然后下半场我就崩溃了;我完全无效的尝试如下所示:

 for (var i=0; i < courseInfo.length; i++) {
    var requestCollection = [];
    for (var j=0; j < courseInfo[i].length; j++) {
      requestCollection.push(studentInfo[i] + courseInfo[j]);
    };

if (requestCollection.length > 0) {
Array.prototype.push.apply(appendValues, requestCollection);
};
};

转换的预期结果是从以下形式的一组行开始:

Jenny, id100, F, English, Science, Math, Physics
Johnny, id101, M, Science, Sports, Gym, English

并产生:

Jenny, id100, F, English
Jenny, id100, F, Science
Jenny, id100, F, Math
Jenny, id100, F, Physics
Johnny, id101, M, Science
Johnny, id101, M, Sports
Johnny, id101, M, Gym
Johnny, id101, M, English

最佳答案

你可以使用 destructuringspread操作,然后映射重新组合。

data = [
  ['Jenny', 'id100', 'F', 'English', 'Science', 'Math', 'Physics'],
  ['Johnny', 'id101', 'M', 'Science', 'Sports', 'Gym', 'English']
];

result = [];
data.map(row => {
  var [name, id, gender, ...prefs] = row;
  prefs.map((x) => result.push([name, id, gender, x]));
})
console.log(result);

正如评论中指出的那样,由于某些功能 might not be available ,这里有一个更保守的选择。

data.forEach(function(row) {
  prefs = row.slice(3);  
  prefs.map(function(x) { result.push([row[0], row[1], row[2], x]) });
})

关于javascript - 给定两个数组,我如何遍历一个数组并插入第二个数组的重复元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56721418/

相关文章:

javascript - JQuery 填充选择框,但发布选项消失后

php - 内爆时复制 PHP 数组中的第一个值

google-apps-script - 在 Google Form 中使用 Google Apps 脚本检查 Google Spreadsheet 中的现有数据

javascript - 如何修复增量按钮将数字添加到值的末尾而不是在 onChange 之后递增

javascript - 为什么使用 jQuery 更改输入框的值后 jQuery UI Datepicker 无法工作?

javascript - 点击 li 应该在其他 div 中打开一个 url 但有一些数据

arrays - 如何向数组添加多个元素?

java - 我可以使用该字符串作为索引将字符串存储在对象数组中吗?

google-apps-script - 脚本无法打开文档(无法访问,请重试)

authentication - BigQuery - GSheet 表上的脚本运行查询不起作用