Counting duplicate cells on multiple rows and columns with Google Spreadsheet

一曲冷凌霜 提交于 2019-12-25 07:01:02

问题


So with Google Apps Script, I have a spreadsheet as following:

A       B       C...
apple   banana  orange...
banana  orange  grape...
banana  apple   orange...
...     ...     ...

...and I want to make it like this:

apple   2
banana  3
grape   1
orange  3

What would be the easiest way to make this possible?

I have tried to use query function on Google Apps Spreadsheet, but since there are multiple columns it is difficult to sort and count. I have also tried to use join and countif function but it tend to get redundant since there are too many columns.

Need help!


回答1:


this should do the work:

function myFunction() {
  var objList={};
  var ss = SpreadsheetApp.getActive().getActiveSheet();
  var data = ss.getDataRange().getValues();
  for(var i in data){
    for(var j in data[i]){
      if(typeof objList[data[i][j]]=="undefined"){
        objList[data[i][j]]=1;
      }
      else{
        objList[data[i][j]]+=1;
      }
    }
  }
  var objTable=[];
  for(var k in objList){
   objTable.push([k,objList[k]]);
  }
  Logger.log(objTable);
  ss.clear();
  ss.getRange(1, 1, objTable.length, objTable[0].length).setValues(objTable);
}


来源:https://stackoverflow.com/questions/21636164/counting-duplicate-cells-on-multiple-rows-and-columns-with-google-spreadsheet

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