Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

google apps script - How to split and transpose results over 2 columns

Not sure how to even approach this. How do I complete the following which has come from a form:

ColA (UniqID)       ColB
41447.9162847222    Name1, Name2, Name3, Name4
41447.9158912037    Name2, Name6, Name9

I would like to end up with:

ColA               B
41447.9162847222   Name1
41447.9162847222   Name2
41447.9162847222   Name3
41447.9162847222   Name4
41447.9158912037   Name2
41447.9158912037   Name6
41447.9158912037   Name9

I can't use VLOOKUP or MATCH as Names may be duplicated in other records but ColA code will always be unique.

T

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

An answer using native spreadsheet functions:

=ArrayFormula(TRANSPOSE(REGEXREPLACE(SPLIT(CONCATENATE(SUBSTITUTE(", "&B:B;", ";CHAR(10)&A:A&CHAR(9)));CHAR(10));"(.*?)(.*)";{"$1";"$2"})))

Disadvantage is that all columns are coerced to text strings with this method. There are workarounds for this, but the formula would get even more ridiculous.


An answer using a Google Apps Script custom function, which also trims leading and trailing spaces in the comma-separated list, as per the request in comments:

function advanceSplit(range1, range2)
{
  var output = [], temp;
  for (var i = 0, length = range1.length; i < length; i++)
  {
    if (range1[i][0])
    {
      var temp = range2[i][0].split(",");
      for (var j = 0, length2 = temp.length; j < length2; j++)
      {
        output.push([range1[i][0], temp[j].trim()]);
      }
    }
  }
  return output;
}

and then invoke in a spreadsheet cell:

=advancedSplit(A:A;B:B)

My anecdotal observation is that for very large data sets, the latter method (custom function) has better performance than the former.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...