【GAS】スプレッドシートにGmailからスクレイピング~日付データと配列化とソート~【第4回】

2022/08/02

前回は、抜き出したデータの見た目を整えて、matchとreplaceを関数化してわかりやすくしました。今回は、日付を取り出して、日付と抜き出したデータを配列に入れて整理します。

目次

今回やること

前回までは、記録だけを取り出していたので、今回からメールから脳トレを実施した日付を取り出し、日付とデータを配列に入れることによって紐づけます。

また、配列の中身は日付の降順になっているので、昇順になるように関数を用います。

配列.push()

配列の末尾に1つ以上の要素を追加することができます。戻り値としては、新しい配列の要素数を返します。

配列.sort()

要素を文字列に変換してから、UTF-16コード単位の値の並びとして比較します。ソートされた結果が返ります。コピーされた別の配列が準備されることはありません。

new Date()

値を日付として扱います。

GAS全体

function myFunction() {
  
  const query ='さんの脳トレ記録をお届けします。';
  const start = 0;
  const max = 10;

  const threads = GmailApp.search(query,start,max);

  const fetchData = (str ,pre ,suf) =>{
    const reg = new RegExp(pre + '.*?' + suf,'g');
    const preg = new RegExp(pre,'g');
    var data = str.match(reg);
    var data1 = null;
    if(data !== null){
      data1 = data[0].replace(preg,'').replace(suf,'');
    }
    return data1;
  };

  const moment = (str1) =>{
    const minute = str1.replace('分',':').replace('秒','.');
    return minute;
  };

  var date10 = [["日付","計算100","人数数え"]];
  var calc1001 = null;
  var people1 = null;


  for(const thread of threads){
    const messages = GmailApp.getMessagesForThread(thread);

    for(const message of messages){
      const plainBody = message.getPlainBody();
      const date = fetchData(plainBody,'日目\\s','(');
      const calc100 = fetchData(plainBody,'計算100\\s・','(');
      const people = fetchData(plainBody,'人数数え\\s・','/6問');

      console.log('日付:'+date);

      if(calc100 !== null){
        calc1001 = moment(calc100);
        console.log('計算100:'+calc1001);
      }
      else{calc1001 = null;}
      if(people !== null){
        const people1 = moment(people);
        console.log('人数数え:'+people1);
      }
      else{people1 = null;}
      date10.push([date,calc1001,people1]);
    }
  }
  console.log(date10);
  date10.sort(function(a,b){
    return new Date(a[0]) - new Date(b[0]);
  });
  console.log(date10);
}

 

実行結果

配列が、日付が古い順に並び替えられました。

最後に

今回は、日付データを取り出し、データと日付を配列化、配列の並び替えをしました。

次回は、スプレッドシートに書き込むときの重複チェック用にGmail IDを取得したり、他の記録も取得できるようにします。