0

我有這種格式的列表,我從Google Analytics API檢索,然後想輸出到Google表格。谷歌腳本/表格:如何基於值聚合行/對象?

['dog', 'brown', 'mammal', 12], 
['cat', 'black', 'mammal', 18], 
['dog', 'brown', 'mammal', 7], 
['goldfish', 'gold', 'chordata', 2] 

如果前三個字符串相同並刪除重複的條目,我想在最後彙總數字。這樣的:

['dog', 'brown', 'mammal', 19], 
['cat', 'black', 'mammal', 18], 
['goldfish', 'gold', 'chordata', 2] 

我想做到這一點的方法之一是編程做在普通的JavaScript /谷歌Apps腳本,或者使用一些圖書館像UnderscoreGS或添加後,在谷歌表的一些功能做列表到工作表。還沒有找到辦法做到這一點呢。建議?

回答

2

嘗試以此爲出發點:

function groupBy(data, columns, sumCol) 
{ 
    data = data || [['dog', 'brown', 'mammal', 12], 
        ['cat', 'black', 'mammal', 18], 
        ['dog', 'brown', 'mammal', 7], 
        ['goldfish', 'gold', 'chordata', 2]]; 

    columns = columns || [0, 1, 2]; // zero-based 

    sumCol = sumCol || 3; 

    var result = {}; 
    var row = []; 
    var key = ''; 
    var value = 0; 
    var prev = 0; 
    for (var numRow = 0, h = data.length; numRow < h; numRow++) 
    { 
    row = data[numRow]; 
    // join another row 
    for(var numColumn = 0, w = row.length; numColumn < w; numColumn++) 
    { 
     if (columns.indexOf(numColumn) > -1) 
     { 
      key = '' + key + row[numColumn] + ','; 

     } 
     else if(sumCol == numColumn) { value = row[numColumn]; }      
    } 
    prev = result[key]; 
    // write result 
    if (prev == undefined) { result[key] = value; } 
    else result[key] += value; 

    value = 0; 
    key = ''; 

    } 

    Logger.log(result); 

} 
相關問題