splice()method allows you to make changes to the contents of an array by removing or replacing existing elements and/or adding new elements in place. If you’re building out a website or application that allows users to type and search for things, assist them in finding products based on their needs and wants and many other things. Arrays can be used for many other things rather than filters. Arrays have their place in a lot of server-side programming as well.
Splice accepts three parameters, which are the arguments that this method will take to complete your requested task(s).
Start — optional
“Start” is the first parament that splice will accept. This is the number of the index you choose to start from. All this is doing is going to index 1, placing “newPerson2” in that index and not removing any of the elements but instead it’s moving it over basically.
Delete Count — optional
This is the second parameter that accepts a number and it represents the number of elements you are planning on replacing starting from the index you have chosen. If you select a number that is larger than the number of elements that currently exist, all those elements will be removed and replaced with the element you’re inserting.
This is the actual element that you will place into your array. This is necessary for adding new elements into your array. If you choose not to add this parameter, the splice method will only remove items from your array. Using splice with a number only as the main parameter will select the element’s position in the array but not the index. For example, array.splice(1), will return the first item of your array. Array.splice(2), will return the first two elements in your array. Since you’re not inserting any new variables by doing this, you won’t have to specify the index of where that element is located.
let array = ['person1', 'person2', 'person3'];array.splice(1, 0, 'newPerson2');//Expected output ---> "person1, newPerson2, person2, person3
For more of my blogs and tutorials, follow me on here!