In my last blog we went over how to store and access arrays. We also learned some simple techniques to add and remove items from the beginning and end of an array. In this article we will look at some more advanced array manipulation techniques
Removing Items Using splice()
Previously we learned how to remove items from the end of an array with 'pop()' and the beginning of an array with 'shift()'. But what if you want to remove items from in-between the beginning and end of an array? Or what if you want to remove more than just one element at a time? This is where we use 'splice()' which allows use to remove any number of consecutive elements from anywhere in the array.
Splice can take up to three parameters but for this removal lesson will will focus on two parameters. The syntax for 'splice()' with two parameters is as follows:
array.splice(index, howmany) // index is where you want to start the splice // howmany is how many item you want to remove
For an example lets look at using
splice() to remove some fruit from our array:
let myArray = ["Banana", "Orange", "Apple", "Mango", "Kiwi"]; let newArray = myArray.splice(2,1) console.log(newArray) // [ 'Apple' ] console.log(myArray) // [ 'Banana', 'Orange', 'Mango', 'Kiwi' ]
As you can see from our example above
splice() can also be use to create a new array with the removed items.
Adding Items Using splice()
In our previous lesson we removed items using two parameters. Using a third parameter you can add items using
splice(). Here is the syntax for adding items:
array.splice(index, howmanytoremove, items to add)
Here is an example of removing items from an array and adding a few items in their place:
let myArray = ["Banana", "Orange", "Apple", "Mango", "Kiwi"]; myArray.splice(2,1,"Blackberries","Strawberries") console.log(myArray) // [ 'Banana', 'Orange', 'Blackberries', 'Strawberries', 'Mango', 'Kiwi' ]
Copying an Array using Slice()
In our previous lessons when using
splice() we modify the original array. Using
slice() we can copy an array leaving the original array intact.
slice() only takes two parameters, the first is the index where the extraction begins and the second is the index where to stop the extraction. One key thing to remember is for that second number the extraction will occur up to but not including that element. Let's look at an example:
let myArray = ["Banana", "Orange", "Apple", "Mango", "Kiwi"]; let myNewFruit = myArray.slice(1,3) console.log(myNewFruit) // [ 'Orange', 'Apple' ] console.log(myArray) // [ 'Banana', 'Orange', 'Apple', 'Mango', 'Kiwi' ]
Notice in the example above we created an new array without changing the original.
Now we know how to remove and add items to any part of array. In our next lesson we will take a look at some more array manipulation techniques.