Here is working code link : http://plnkr.co/edit/SHfpFQ?p=preview
Splice is an effective way to add, replace or remove elements from specific index in Javascript Array.
Javascript array splice() method changes the content of an array, adding new elements while removing old elements.
Syntax
Its syntax is as follows −
array.splice(index, howMany, [element1][, ..., elementN]);
Parameter Details
- index − Index at which to start changing the array.
- howMany − An integer indicating the number of old array elements to remove. IfhowMany is 0, no elements are removed.
- element1, …, elementN − The elements to add to the array. If you don’t specify any elements, splice simply removes the elements from the array.
Return Value
Returns the extracted array based on the passed parameters.
If you specify a different number of elements to insert than the number you’re removing, the array will have a different length at the end of the call.
Examples
Using splice()
The following script illustrates the use of splice()
:
var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];
// removes 0 elements from index 2, and inserts 'drum'
var removed = myFish.splice(2, 0, 'drum');
// myFish is ['angel', 'clown', 'drum', 'mandarin', 'surgeon']
// removed is [], no elements removed
// removes 1 element from index 3
removed = myFish.splice(3, 1);
// myFish is ['angel', 'clown', 'drum', 'surgeon']
// removed is ['mandarin']
// removes 1 element from index 2, and inserts 'trumpet'
removed = myFish.splice(2, 1, 'trumpet');
// myFish is ['angel', 'clown', 'trumpet', 'surgeon']
// removed is ['drum']
// removes 2 elements from index 0, and inserts 'parrot', 'anemone' and 'blue'
removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
// myFish is ['parrot', 'anemone', 'blue', 'trumpet', 'surgeon']
// removed is ['angel', 'clown']
// removes 2 elements from index 3
removed = myFish.splice(3, Number.MAX_VALUE);
// myFish is ['parrot', 'anemone', 'blue']
// removed is ['trumpet', 'surgeon']
Reblogged this on SutoCom Solutions.
LikeLike