简体   繁体   中英

Find difference between two arrays (missing values) in Google Apps Script

Trying to find a method that works in Google Apps Scripts, to compare two arrays and find the values missing in the second array.

I've tried several approaches but can't find one that works in GAS. Currently attempting with a for() loop and indexOf():

var ss = SpreadsheetApp.getActiveSpreadsheet();  
var sheet = ss.setActiveSheet(ss.getSheetByName('test'));

function TEST(){
  var lastRow = sheet.getLastRow();
  var orders = sheet.getRange(2,1,lastRow,1).getValues(); //[a,b,c,d]
  var products = sheet.getRange(2, 2,lastRow,1).getValues();  //[a, b]
  var missing = [];
  for ( var i = 0 ; i < Object.keys(orders).length; i++){
    if(products.indexOf(orders[i])<0){
      missing.push(orders[i]);};
  };
  Logger.log(missing); //expect [c, d]
   }

The source table has two columns to compare, and a 3rd column where the new 'missing' array should be stored.

orders  products    missing
a       a           c
b       b           d
c       
d       

I tried methods from several other posts but everything is using functions that aren't available in Google Apps Scripts.

Find Missing Orders:

function findMissingOrders() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Sheet110');
  var orderA=sh.getRange(2,1,getColumnHeight(1)-1,1).getValues().map(function(r){return r[0];});
  var prodA=sh.getRange(2,2,getColumnHeight(2)-1,1).getValues().map(function(r){return r[0];});
  var missA=[];
  for(var i=0;i<orderA.length;i++) {
    var order=orderA[i];
    if(prodA.indexOf(orderA[i])==-1) {
      missA.push([orderA[i]]);
    }
  }
  if(missA.length>0) {
    sh.getRange(2,3,missA.length,1).setValues(missA);
  }
}

Here's the getColumnHeight() function:

function getColumnHeight(col,sh,ss){
  var ss=ss || SpreadsheetApp.getActive();
  var sh=sh || ss.getActiveSheet();
  var col=col || sh.getActiveCell().getColumn();
  var rg=sh.getRange(1,col,sh.getLastRow(),1);
  var vA=rg.getValues();
  while(vA[vA.length-1][0].length==0){
    vA.splice(vA.length-1,1);
  }
  return vA.length;
}

Spreadsheet Before:

在此处输入图片说明

Spreadsheet After:

在此处输入图片说明

Have you tried using .filter() on the orders variable? Something like this should do the trick:

var orders = sheet.getRange(2,1,lastRow,1).getValues().map(firstOfArray)
var products = sheet.getRange(2, 2,lastRow,1).getValues().map(firstOfArray)
var missing = orders.filter(missing)

function firstOfArray(array) {
   return array[0]
}
function missing(order) {
    return products.indexOf(order) === -1
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM