I have a column with data in google sheets like this:
col_name
A
A
A
B
B
C
I want to store this data in a dictionary where column value is a key and number of occurrences is a value:
dict = {A:3, B:2, C:1}
I tried to iterate through a list of values:
col_values = mySheet.getRange(2, col, last_row-1, 1).getValues();
With a function:
function count_occurances_in_col(col_values){
let occurances_dict = new Map();
for(var i=0;i<=col_values.length;i++){
if(occurances_dict.has(col_values[i][0])){
let value = occurances_dict.get(col_values[i][0]);
occurances_dict.set(col_values[i][0], value+1);
} else {
occurances_dict.set(col_values[i][0], 1);
}
}
return occurances_dict;
};
But the function returns undefined instead of a dictionary (perhaps) because keys are set dynamically (if I understood correctly the forums – I don’t know JS well, only python).
Can I obtain such a dict with some function or any other way?
Notice that getValues() method returns col_values in a form:
[[A], [A], [A], [B], [B], [C]]
3
Answers
This should work
The simplest way to get a dictionary is to use a plain vanilla Object, like this:
The
test()
function will log and return the result in the format{ A: 3, B: 2, C: 1 }
.Here is an example using Set to get the unique values of col_values and then count the number of occurances.
Code.gs
Execution log