Skip to content Skip to sidebar Skip to footer

Filtering A Two Dimensional Array In Apps Script

In apps script I have the following: function diff(A, B) { return A.filter(function (a) { return B.indexOf(a) == -1; }); } When I run: function testArray(){ ta = ['a','

Solution 1:

You problem is related to the fact that in javascript [1, 2, 3] != [1, 2, 3]. Arrays and object comparisons are not done by the values. This also applies to indexOf(). For example:

var a = [[1, 2, 3], [4, 5, 6]]
var b = [4, 5, 6]

console.log(a.indexOf(b)) // returns -1

To fix this you need to write a function that defines equality the way you want. For example:

// arrays with the same values in the same order will be considered equalfunctionarray_equals(a, b){
    return a.length === b.length && a.every((item,idx) => item === b[idx])
}

console.log(array_equals([1, 2, 3], [1, 2, 3]))
console.log(array_equals([1, 2, 3], [1, 2, 4]))

With that in hand you can now filter with something like:

var a = [[1,2,3], [4, 5, 6], [7, 8, 9]]
var b = [[1, 2, 3], [4, 5, 6]]


functionarray_equals(a, b){
    return a.length === b.length && a.every((item,idx) => item === b[idx])
}

functiondiff(A, B) {
    return A.filter(test => {
      return B.findIndex(item =>array_equals(item,test)) == -1;
    });
  }
console.log(diff(a,b))

Solution 2:

You want to retrieve [[a, s, d, f, g], [q, w, e, r, t]] from [[a, a, a, a, a], [z, x, c, v, b], [m, n, b, v, c], [a, s, d, f, g], [q, w, e, r, t]] and [[a, a, a, a, a], [z, x, c, v, b], [m, n, b, v, c]]. If my understanding is correct, how about this sample script? I think that there are several answers for your situation. Please think of this as one of them.

Sample script :

var res = values.filter(
   function(e) {
      return target_sheet_values.filter(
         function(f) {
            return e.toString() == f.toString()
         }).length == 0
   });

var target_sheet_values = [
   ["a","a","a","a","a"],
   ["z","x","c","v","b"],
   ["m","n","b","v","c"]
];
var values = [
   ["a","a","a","a","a"],
   ["z","x","c","v","b"],
   ["m","n","b","v","c"],
   ["a","s","d","f","g"],
   ["q","w","e","r","t"]
];

var res = values.filter(
   function(e) {
      return target_sheet_values.filter(
         function(f) {
            return e.toString() == f.toString()
         }).length == 0
   });
console.log(res);

Result

[["a","s","d","f","g"],["q","w","e","r","t"]]

Note :

  • values and target_sheet_values are from your script.
  • When you use this, for your script, please use this instead of var diff_values = diff(values, target_sheet_values).

If I misunderstand what you want, please tell me. I would like to modify it.

Post a Comment for "Filtering A Two Dimensional Array In Apps Script"