I am trying to splice a 2D array in Google Apps Script. I have the following code, but it only works with a 1D array:
function trimArray() {
var myArray = ['1', '2', '3', '4', '5', '6,', '7', '8', '9', '10'];
myArray.splice(3, myArray.length);
console.log(myArray);
}
How do I modify the code above to work with this array?
[['1', '2', '3', '4', '5', '6,', '7', '8', '9', '10']]
The output should be the same as the function above, but still maintain a 2D array:
[['1', '2', '3']]
CodePudding user response:
Try this:
function splicearray() {
let arr = [[1,2,3],[7,8,9]];
arr.splice(1,0,[4,5,6]);
Logger.log(arr);
}
Execution log
2:11:54 PM Notice Execution started
2:11:54 PM Info [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]
2:11:55 PM Notice Execution completed
I don't understand your example if I wanted to be left with a 2 d array as you show I would do it this way:
function trimArray() {
let arr = [['1', '2', '3', '4', '5', '6,', '7', '8', '9', '10']];
arr.splice(0,1, [1,2,3]);
Logger.log(arr);
}
Execution log
2:23:26 PM Notice Execution started
2:23:26 PM Info [[1.0, 2.0, 3.0]]
2:23:27 PM Notice Execution completed
CodePudding user response:
Try this one
function test() {
try {
let a = [['1', '2', '3', '4', '5', '6,', '7', '8', '9', '10']];
a[0] = a[0].slice(0,3);
console.log(a)
}
catch(err) {
console.log("Error in test: " err);
}
}
2:59:19 PM Notice Execution started
2:59:20 PM Info [ [ '1', '2', '3' ] ]
2:59:20 PM Notice Execution completed