Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

Google Apps Scriptを使って2つの2次元配列の差分を取得したい

More than 1 year has passed since last update.

概要

Google Apps Script (GAS)ではGoogle DocsやGoogle APIsなどで2次元配列が頻繁に使われています。このとき、2つの配列から差分の要素を必要とする場合があります。サンプルではこのような差分を取得します。

サンプル

差分を取得するためのサンプル

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"]]

ちなみに、スクリプトの== 0> 0に変更すると重複した要素を取得することができます。

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"]]

最近の測定でGASのループ手法ではmap, filterが有効であることを知りましたので、早速取り入れてみました。

tanaike
Google Developer Expert (GDE) in Google Workspace
https://tanaikech.github.io/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away