【问题标题】:How to split strings in multiple columns into multiple rows如何将多列中的字符串拆分为多行
【发布时间】:2021-11-23 09:17:52
【问题描述】:

我正在处理一个包含多个用字符串填充的列的工作表。我需要拆分字符串并让目标列 E、F、G 重复与右侧最长字符串的列相同的次数。

发件人: 收件人:

这是sample worksheet.的链接

我之前使用的脚本虽然可以拆分工作表中的所有字符串,但是如果在 E 列停止。我想知道我是否可以修改此脚本,以便它可以满足右侧剩余的列。这是脚本:

const result = range =>
  range.flatMap(([a, ...v]) => {
    const { vv, len } = v.reduce((o, c) => {
      const t = c.split(",");
      o.vv.push(t);
      o.len = o.len < t.length ? t.length : o.len;
      return o;
    }, { vv: [], len: 0 });
    const temp = vv.map(e => e.concat(Array(len - e.length).fill("")));
    return temp[0].map((_, c) => [a, ...temp.map(r => r[c])]);
  });

【问题讨论】:

标签: javascript arrays google-apps-script google-sheets


【解决方案1】:

在你的情况下,下面的修改脚本怎么样?

修改脚本:

const result = range =>
  range.flatMap(([a, b, c, d, e, f, g, ...v]) => {
    const { vv, len } = v.reduce((o, c) => {
      const t = typeof c != "string" ? c.toString().split(",") : c.split(",");
      o.vv.push(t);
      o.len = o.len < t.length ? t.length : o.len;
      return o;
    }, { vv: [], len: 0 });
    const temp = vv.map(e => e.concat(Array(len - e.length).fill("")));
    return temp[0].map((_, i) => [...(i == 0 ? [a, b, c, d] : Array(4).fill("")), e, f, g, ...temp.map(r => isNaN(r[i].trim()) ? r[i].trim() : r[i].trim() && Number(r[i]))]);
  });
  • 在此修改中,不处理“A”到“D”列。并且,为每一行复制列“E”到“G”。并且,“H”之后的列拆分值。

结果:

当这个脚本运行时,得到如下结果。

注意:

  • 在此脚本中,使用了您的示例电子表格。因此,当您的实际电子表格与示例电子表格不同时,可能无法使用该脚本。请注意这一点。

参考资料:

【讨论】:

  • !这完美地工作。你是个天才!再次对给您带来的不便深表歉意,并非常感谢您付出的时间和精力。
  • @Phronimos 感谢您的回复。我很高兴你的问题得到了解决。也谢谢你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-31
相关资源
最近更新 更多