My JavaScript code returns different outputs when run locally and when run in Google Sheets. The code below takes 2 arrays (one contains labels, one contains data) and sum the data according to the label:
function removeDuplicateSum(label, data) {
var result = {};
for (var i = 0; i < label.length; i++) {
if (label[i] in result) result[label[i]] += data[i];
else result[label[i]] = data[i];
};
return result;
}
And here's a sample output:
function printObject(obj) {
// helper function to print the object
return JSON.stringify(obj);
}
c = [1, 2, 3, 4, 5]
b = ['a', 'a', 'b', 'b', 'c']
console.log(printObject(removeDuplicateSum(b, c)));
>>> {"a":3,"b":7,"c":5} // Correct output
But when I use it as a custom function in Google Sheets, it returns an empty object:
And the output in that cell is simply an empty string (""
). I expect it to return this string "{"a":3,"b":7,"c":5}".
I also have another function which returns an int
locally but returns a string
in Google Sheets - another example of how JavaScript works differently in Google Sheets.
Why does my JavaScript code work so differently in Google Apps Script (and specifically in Google Sheets)? And where can I find a reference on the differences between Google Apps Script and the JavaScript used in a web environment?
Thanks a lot.