简体   繁体   中英

Google scripts function comparing two ranges working in console but not in sheets

Diffing two user ranges in Google Sheets, this works in console but doesn't work in the sheet. Can someone please explain why?

function DIFF(a, b) {
  return a.filter(function(v){
     return b.indexOf(v) === -1 ? true : false;
  }).length
}

When you pass a range to a custom Sheets function, it gets either

  • a single value, if the range consists of one cell, or
  • a double array otherwise. Even if the range is one dimensional: for example, you get [[1], [2], [3]] for a column range or [[1, 2, 3]] for a row range.

Your DIFF function assumes that the arguments are ordinary arrays of values. So you need to flatten double arrays, or turn a single value to an array. This is what the function flatten does.

function flatten(arg) {
  if (arg.constructor === Array) {
    return arg.reduce(function(a, b) {
      return a.concat(b);
    });
  }
  else {
    return [arg];
  }
}

Then DIFF can be like this:

function DIFF(a, b) {
  a = flatten(a);
  b = flatten(b);
  return a.filter(function(v) {
     return b.indexOf(v) === -1;
  }).length
}

(Aside: ternary operator : ? true : false was redundant here, so I removed it.)

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