Retrieve Difference Between 2 Dimensional Arrays using Google Apps Script

Gists

This sample script retrieves the difference elements between 2 dimensional arrays using Google Apps Script. In Google Apps Script, 2 dimensional arrays are often used at Google Docs and Google APIs. And from my recent report, it has already found that the process cost of filter() is the lowest in the other loop methods. So I use the script like this.

var ar1 = [["a1", "b1", "c1"], ["a2", "b2", "c2"], ["a3", "b3", "c3"], ["a4", "b4", "c4"], ["a5", "b5", "c5"]];
var ar2 = [["a2", "b2", "c2"], ["a5", "b5", "c5"], ["a1", "b2", "c3"]];

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

Logger.log(res); // [["a1","b1","c1"],["a3","b3","c3"],["a4","b4","c4"]]

For above script, when it changes from == 0 to > 0, the duplication elements can be retrieved as follows.

var ar1 = [["a1", "b1", "c1"], ["a2", "b2", "c2"], ["a3", "b3", "c3"], ["a4", "b4", "c4"], ["a5", "b5", "c5"]];
var ar2 = [["a2", "b2", "c2"], ["a5", "b5", "c5"], ["a1", "b2", "c3"]];

var res = ar1.filter(function(e) {return ar2.filter(function(f) {return e.toString() == f.toString()}).length > 0});

Logger.log(res); // [["a2","b2","c2"],["a5","b5","c5"]]

 Share!