I am trying to find some questions to answer and found myself in a pinch when trying to answer one.
The question is to duplicate a row whenever a certain value in a column is found. And the duplicated row should be modified so that the certain value found is changed.
I created this script to solve the said question:
const data = [
[1, 2, 3, true, 5, 6],
[7, 8, 9, false, 10, 12]
];
var output = [];
function unexpectedOutput() {
data.forEach(row => {
// first push
output.push(row);
if (row[3]) {
row[3] = false;
// second push IF row[3] is true
output.push(row);
}
});
console.log(output);
}
Output to be expected here is:
[ [ 1, 2, 3, true, 5, 6 ],
[ 1, 2, 3, false, 5, 6 ],
[ 7, 8, 9, false, 10, 12 ] ]
But I get
[ [ 1, 2, 3, false, 5, 6 ],
[ 1, 2, 3, false, 5, 6 ],
[ 7, 8, 9, false, 10, 12 ] ]
I see that the answer is solved here by redefining a variable from scratch (not equate to row) and that user also experience the same issue but didn't get the explanation as to why the issue happens.
Seems like pointers to me but as I recall, there are nothing like that in JavaScript, so what happened there? The above code is tested in Google Apps Script by the way.