Injecting Data Into an Array using Splice


When you use Array.push(), you're only appending to the end of the array. Sometimes, you'll want to insert data into the middle of the array or replace a value in the array. To do this, you can use the Array.splice() method, which is a much cleaner way to manipulate your array's data.

// Array.splice(starting_position, positions_to_delete, new_value) // injecting a new value yourArray.splice(2,0,"new value") // replacing an existing value yourArray.splice(0,1,"new value")

For example, let's say you had two arrays of data. One of them is a nested array of crypto coin data pulled from your Google Sheet and the other is a price update for one of the coins.

let array1 = [['Coin', 'Price'],['DOGE', '0.089'], ['BTC', '37854.34']] let array2 = ['DOGE', '0.223']

You wouldn't want to just append the data in this case and you also wouldn't want to try to recreate the entire data array. The best thing to do is to find the matching row and replace the existing price with the new price. By using the Array.splice() method after you've located it's position, you can quickly manipulate your array's data without much hassle or complex logic.

let array1 = [['Coin', 'Price'],['DOGE', '0.089'], ['BTC', '37854.34']] let array2 = ['DOGE', '0.223'] console.log("before", array1) // output: [ [ 'Coin', 'Price' ],[ 'DOGE', '0.089' ],[ 'BTC', '37854.34' ] ] for (let item in array1) { if(array1[item][0] == array2[0]) { array1.splice(item, 1, array2) } } console.log("after", array1) // output: [ [ 'Coin', 'Price' ],[ 'DOGE', '0.223' ],[ 'BTC', '37854.34' ] ]



There are plenty of ways to use the Array.splice() method, but I tend to use it mostly for combining one or more data sets into an existing one.

thumbnail

NitroGAS Chrome Extension

Want to reference this code snippet right from your Google Apps Script Project? Check out our NitroGAS Chrome Extension. This tool will help you build your scripts faster than you could imagine. The tool itself and access to the code snippets are 100% FREE - Happy Coding!

Get the Extension