I currently use the below function to count the occurances of the same value in a column.
function countRecords() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const last = sheet.getLastRow();
const range = 'B1:A' + last ;
const data = sheet.getRange(range).getValues();
const counts = {};
data.forEach(function (x) { counts[x] = (counts[x] || 0) + 1; });
var result = Object.entries(counts);
return result;
}
This results in an array with each unique value and a count of how many times it appears in the column. I now have a requirement to only count the value if another value in column k on the row exists.
For Example
COL B | COL K |
---|---|
Val1 | |
Val1 | |
Val1 | Something |
Val1 | something |
Val2 | Something |
Val2 | something |
Val2 |
I would expect the output to be [Val1, 2][Val2, 1], it should only count the rows where COLK is empty.
I have tried nesting loops but I am getting more confused as I go and would appreciate some help.
function countRecords() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lr = sheet.getLastRow();
var lc = sheet.getLastColumn();
var data = sheet.getRange(1, 2, lr, lc - 1).getValues(); // If column K is the last column, use lc-1. Otherwise, manually change it to 10.
var fitleredData = data.map(x=>[x[0],x[x.length-1]]);
var colA = fitleredData.filter(x => x[1] == "").flat().filter(x => x != "");
var newColA = Array.from(new Set(colA));
var count = newColA.map(x => colA.filter(y => y == x).length);
var out = newColA.map((x, i) => [x, count[i]])
console.log(out)
}
COL B | COL K |
---|---|
Val1 | |
Val1 | |
Val1 | Something |
Val1 | something |
Val2 | Something |
Val2 | something |
Val2 |
[ [ 'Val1', 2 ], [ 'Val2', 1 ] ]