LANG SELRCT

Apps Script Reference  (Create: Create new Spreadsheet | Create new Apps Script

Tuesday, August 10, 2021

配列内で重複する値の発生数を取得する(二次元配列で返す)


const values = [1, 2, 3, 2] のそれぞれの数値の件数を取得したい

このように
[[1, 1], [2, 2], [3, 1]]

1は1つ
2は2つ
3は1つ



コード.gs
function getCountValues() {
  const values = [1, 2, 3, 2];
  const countValues = returnCountValues(values);
  Logger.log(countValues);
}

function returnCountValues(values) {
  const sortedValues = values.sort();
  const unique = sortedValues.filter(returnUnique);

  let arrays = [];
  for(let i = 0; i < unique.length; i++) {
    const value = unique[i];
    const count = findDup(value, values);
    arrays.push([value, count]);
  }
  return arrays;
}

function findDup(value, values) {
  let count = 0;
  for(let i = 0; i < values.length; i++) {
    if(values[i] === value) {
      count++;
    }
  }
  return count;
}

function returnUnique(value, index, array){
  var valueIndex = array.indexOf(value);
  var result = valueIndex === index;
  Logger.log([array, "の中で", value, "は", valueIndex, "番目にあって、現在のindexは", index, "なのでuniqueの配列への追加は", result])
  return result;
}
意訳
これを実行する
valuesを決める
returnCountValuesに渡して
結果をログに出す


valuesの要素ごとの件数を返す
values並べ替える→1,2,2,3
それをユニークにする→1,2,3

結果を入れる配列を用意する
uniqueの数だけ繰り返す
uniqueをひとつずつ取り出して
values内の重複を探して
arraysに追加する

完成したarraysを返す


重複を見つける
countの初期値を0にしておく
valuesの数だけ繰り返す
もしvalues内にvalueと同じ値があれば
countに1追加していく


countを返す


ユニークを返す
arrayの中でvalueが何番目にあるか
それが現在のvalueの位置と同じならtrue, 違うならfalse
ログに出してみる
を返してtrueだけのunique配列を作る


実行結果

[[1.0, 1.0], [2.0, 2.0], [3.0, 1.0]]

returnUniqueの中で何をやっているのかログで確認しています。




別の書き方


コード.gs
function getCountValues(){
  const values = [1,2,3,2,2,2,3,3,3];
  const arrays = returnCountValues(values);
  Logger.log(arrays);
}

function returnCountValues(values) {
  let arrays = [];
  let count = 1;
  let currentIndex = 0;
  const sortedValues = values.sort();
  for(let i = 0; i < sortedValues.length; i++) {
    if(sortedValues[i] === sortedValues[i-1]) {
      count++;
      arrays[currentIndex-1] = [sortedValues[i], count];
    } else {
      count = 1;
      arrays.push([sortedValues[i], count])
      currentIndex++;
    }
  }
  return arrays;
}

実行結果


Latest post

Extracting data from Google Sheets with regular expressions

Introduction Regular expressions are a powerful tool that can be used to extract data from text.  In Google Sheets, regular expressions ca...