The array splice method for removing an injecting elements in an array
The array splice method is often confused with the array slice method, that is some what similar, but they work in very different ways. The array slice method will return a new array from a source array from a given starting and ending index value without mutating the source array from which it is called. The splice method will remove one or more elements from a starting index, and it can also be used to inject elements at that index location while I am at it. Unlike the slice method the splice method will mutate the array in place, but one thing that is similar might be the return value of the splice method as that will be a new array of the elements that are in a given index range.
1 - The basics of the array splice method
1.1 - Just remove some elements from an array
First off if I just want to remove one or more elements from an array, and do not care if I am mutating the array in place the process of using the array splice method is fairly simple. I just call the array splice method off of the instance of the array that I want to mutate and give an array index as the first argument. I will then want to give a number of elements that I would like to remove from the array at the given array index location.
1.2 - The return value
Another thing to check out is what the return value of the array splice method is. Just like the array slice method the return value is a new array that is a collection of elements from a starting index to another location in the array. The difference is that with the array slice method an end index value is given rather than a number of elements, and with array slice the source array is not changed.
1.3 - remove and inject
Another thing about the array splice method is that it can not just be used to remove elements, and get a range of elements from an array while doing so. It can also be used as a way to go about injecting elements into an array at the given index location. When doing so I can just give or more more elements to inject at the index location in the from of additional arguments.
If I given an array as the element to inject at the index location then the result will be that array at the location. In some situations this is what I would want, but if I want the children to be injected doing so is a little involved. One way to go about doing so would be to make use of the function apply prototype method, and then using the array concat method as a way to create an array of arguments to give to the apply function prototype method.
1.4 - Remove zero elements and just inject
When it comes to injecting elements I have the option to set the number of elements that I want to inject as 0. This way I can use the array splice method as a way to just inject elements at an index location without removing anything at all.
2 - Conclusion