Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Last active September 24, 2023 13:04
Show Gist options
  • Save tanaikech/2abf57eefc667d6c71310db6aa95a44d to your computer and use it in GitHub Desktop.
Save tanaikech/2abf57eefc667d6c71310db6aa95a44d to your computer and use it in GitHub Desktop.
Retrieve Difference Between 2 Dimensional Arrays using Google Apps Script

Retrieve Difference Between 2 Dimensional Arrays using Google Apps Script

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"]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment