これは、範囲の値を反復処理する非常に汎用的な関数です。また、その上で機能を実行するために使用することもできますreduce
(これはあなたの場合に役立ちます)。要素の最初の要素だけを見つけたい場合は、ループから抜け出すこともできます。
値の配列の代わりに実際の Range インスタンスを受け入れるように、非常に簡単に変更できます。
function range_reduce(rangeValues,fn,collection) {
collection = collection || [];
var debug_rr = "<<";
for(var rowIndex = 0, row=undefined; rowIndex<rangeValues.length && (row = rangeValues[rowIndex]); rowIndex++) {
for(var colIndex = 0, value=undefined; colIndex<row.length && (value = row[colIndex]); colIndex++) {
try {
collection = fn(collection, value, rowIndex, colIndex);
} catch (e) {
if(! e instanceof BreakException) {
throw e;
} else {
return collection;
}
}
}
}
return collection;
}
// this is a created, arbitrary function to serve as a way
// to break out of the reduce function. Your callback would
// `throw new BreakException()` and `rang_reduce` would stop
// there and not continue iterating over "rangeValues".
function BreakException();
あなたの場合:
var range = SpreadsheetApp.getActiveSheet().getActiveRange()
var writeValues = range_reduce(range.getValues(), function(collection, value, row, col) {
collection[row] || collection.push([]);
collection[row].push(value + " string");
});
range.setValues(writeValues)