我想我完全想多了,但我無法擺脫我的頭腦。在 Google 表格中,我有一個如下所示的工單串列:
Work ID Location Start Time Officer Count
123 North 1100
123 North 1100
123 North 1100
222 South 1200
999 North 1400
999 North 1400
333 South 1200
每個工單總是有一個官員分配給它,所以我需要計算重復的工單并將它們推送到“官員計數”下的陣列末尾,以便顯示需要多少個官員。例如,123 需要 3,222 需要 1,999 需要 2,333 需要 1。
但是,我現在的代碼彈出了正確的計數,只是從原始二維陣列中亂序,所以我不能將它推到陣列的末尾。有什么建議么?
var rowRange = sheet.getRange(2, 1, 7, 3).getValues();
//Create Work Number array (1D array)
var oneDArr = rowRange.map(function(row){return row[0];});
//Create object to count number of officers to Work Number
var counts = {};
oneDArr.forEach(function(x) { counts[x] = (counts[x] || 0) 1; });
//Create Array from Object
var array = [];
var array = Object.entries(counts);
//Set Values to correct location
// sheet.getRange(11, 1, array.length, array[0].length).setValues(array);
}
uj5u.com熱心網友回復:
描述
這是一個示例腳本,用于獲取作業訂單的數量并將它們放入原始陣列中。
代碼.gs
function test () {
try {
let sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
let values = sheet.getDataRange().getValues();
values.shift(); // remove the headers
let ids = values.map( row => row[0] );
ids = [...new Set(ids)]; // create an array of unique ids
console.log(ids);
let count = ids.map( id => 0 ); // initialize count to 0
values.forEach( row => { let index = ids.indexOf(row[0]);
count[index] ;
});
console.log(count);
// now let put back into spreadsheet
ids.forEach( (id,i) => { let j = values.findIndex( row => row[0] === id );
values[j][3] = count[i]; } );
console.log(values);
}
catch(err) {
console.log(err);
}
}
執行日志
8:46:20 PM Notice Execution started
8:46:23 PM Info [ 123, 222, 999, 333 ]
8:46:23 PM Info [ 3, 1, 2, 1 ]
8:46:23 PM Info [ [ 123, 'North', 1100, 3 ],
[ 123, 'North', 1100, '' ],
[ 123, 'North', 1100, '' ],
[ 222, 'South', 1200, 1 ],
[ 999, 'North', 1400, 2 ],
[ 999, 'North', 1400, '' ],
[ 333, 'South', 1200, 1 ] ]
8:46:21 PM Notice Execution completed
參考
- 陣列.shift()
- 陣列.map()
- 設定物件
- Array.forEach()
- Array.indexOf()
- Array.findIndex()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/494449.html
標籤:谷歌应用脚本
上一篇:在Google表格中加載對話框
