Using Arrays (integer, index, associative array)

6. The splice() Method

          The splice() method allows us to add and/or remove items to or from an array, and to specifically indicate the index of the elements that have to be added or removed.

For example:

var fruit = ["apple", "peach", "orange", "lemon", "lime", "cherry"];

fruit.splice(2, 0, "melon", "banana");

console.log(fruit); //Prints ["apple", "peach", "melon", "banana", "orange", "lemon", "lime", "cherry"] 


            The method splice() requires at least 2 parameters. The first parameter refers to the index that specify the position of the array item which will be added or removed. The second parameter will be the number of items to be removed. In the example, it is set to 0, - which means that no items will be removed. The succeeding parameters are optional. It is assigned to item/s that will be added to the array. Another example below will show how removing an item is done using splice().


var fruit = ["apple", "peach", "orange", "lemon", "lime", "cherry"];

fruit.splice(2, 1);

console.log(fruit); //Prints ["apple", "peach", "lemon", "lime", "cherry"]


             Take note that combining the two examples above would allow the use of the splice() method to both add and remove elements to and from an element at the same time.