xyz
xyz

Reputation: 2300

Remove a row from an Array of values by row index

I want to remove rows from an array by row Index

I have

function test() {
arr1 = [[Id, From, To], [1.0, AA1, BB1], [2.0, AA2, BB2], [3.0, AA3, BB3], [4.0, AA4, BB4], [5.0, AA5, BB5], [6.0, AA6, BB6]]

arr1.splice(1,1);
return arr1
}

I get

[[Id, From, To], [2.0, AA2, BB2], [3.0, AA3, BB3], [4.0, AA4, BB4], [5.0, AA5, BB5], [6.0, AA6, BB6]]

Whitch is what I want

But If I have instead

function test() {
var sht = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
arr1 = [[Id, From, To], [1.0, AA1, BB1], [2.0, AA2, BB2], [3.0, AA3, BB3], [4.0, AA4, BB4], [5.0, AA5, BB5], [6.0, AA6, BB6]]

var result = arr1.splice(1,1);

sht.getRange(1,1,result.length,result[0].length).setValues(result)
}

I get

result = [[1.0, AA1, BB1]]

I do not get what is going on, how do I get

result = [[Id, From, To], [2.0, AA2, BB2], [3.0, AA3, BB3], [4.0, AA4, BB4], [5.0, AA5, BB5], [6.0, AA6, BB6]]

Upvotes: 1

Views: 8962

Answers (1)

0Valt
0Valt

Reputation: 10345

Please, carefully read the documentation on splice() method. When invoked on an Array, it takes three possible arguments:

  1. start - index of Array element to start from;
  2. deleteCount - number of elements to delete starting from start;
  3. item - comma-separated list of values to replace deleted values by.

Scenario 1

As you invoke it with two arguments splice(1,1), the method starts from index 1 ([1.0, AA1, BB1]), deletes only this element and replaces it with nothing, mutating the original Array as expected.

Scenario 2

The method also returns all elements you deleted as a separate Array, if you want to return the original Array (mutated by splice()), you will need to remove the var result and return the arr1 directly.

Useful links

  1. splice() method reference;

Upvotes: 5

Related Questions