Friday, March 30, 2018

Array methods splice in detail


We have already seen some array methods, now we can see some other important methods.

The syntax of splice method is,

arr.splice(index[, deleteCount, elem1, ..., elemN])

index - specifying the position.

deleteCount - specifying the count of deleted elements.( don't confuse, we can see example)


1. First let start with deletion, see below example.



let arrTest = ["I", "study", "JavaScript"]; // Index start from 0

arrTest.splice(1, 1); // from index 1 remove 1(deletedcount) element

alert( arrTest ); // ["I", "JavaScript"]



2. Remove and Replace with other elements.


let spliceTest = ["I", "study", "JavaScript", "right", "now"];

spliceTest.splice(0, 3, "Let's", "dance"); // 0 is index;
                             3 - delete count ; 
                             remaining is for insert element

alert( spliceTest ) //  ["Let's", "dance", "right", "now"]


3. How to store removed array elements ?


let normalArray = ["I", "study", "JavaScript", "right", "now"];

// remove 2 first elements
let removedArrayElement = normalArray.splice(0, 2);

alert( removedArrayElement ); // "I", "study" <-- removed elements from an array

3. I do not want to remove an elements, but I need to insert with splice. How ?



let Originalarr = ["I", "study", "JavaScript"];

// from index 2
// delete 0 --> This is important point here
// then insert "complex" and "language"
Originalarr.splice(2, 0, "complex", "language");

alert( Originalarr ); // "I", "study", "complex", "language", "JavaScript"


4. Can I go ahead with negative indexes ?

Negative indexes are allowed in splice. It specify the position from the end of the array.

-1 means, one step back from end
-2 means, two step back from end and so on....


Example is below...



let arrNegativeEg = [1, 2, 5];

// from index -2 (two step from the end)
// delete 0 elements,
// then insert 3 and 4
arrNegativeEg.splice(-2, 0, 3, 4);

alert( arrNegativeEg ); // 1,3,4,2,5








No comments:

Post a Comment