2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2018-05-07

概要

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が有効であることを知りましたので、早速取り入れてみました。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?