How to add and remove items in middle array elements in javascript using splice JavaScript Array Method

Hi friends in this post I am sharing how to add and remove array elements in middle of jusing using splice javascript array method. We know, we can use pop and push for removing array elements.Shift and unshift methods are used to add and remove array elements from first.Also we have explained how to add and remove array elements using array length property.


splice-javascript-array-method




How to Add items in middle of array element?

Copy and paste the below code in notepad and save as index.html .Then open with the browser.
In the below the yellow highlighted color is the important .The value 2 specifies where to add the items geography and history in array element .Here the array element 2 is (i.e) book[2] is maths which is the second array element here.So geography and history will be added before the maths.But wait here is another value 3 . The value 3 specifies how much items should be deleted after the added items.After adding items we will have  english,science,Geography,History,maths,zoology,botany . Now maths,zoology,botany will be removed because we have given value 3.If we have given 0 instead of 3 .Then no items will be removed .It just displays  english,science,Geography,History,maths,zoology,botany .


<button onclick="functiontoaddelement()">Click here to add  Array Elements
in Middle For Each Click</button>
<p id="abc"></p>
<script>
var books=['english' , 'science','maths','zoology','botany'];
document.getElementById("abc").innerHTML = books;
function functiontoaddelement() {
books.splice(2, 3, "Geography", "History");document.getElementById("abc").innerHTML =books;
}
</script>
Also the check the the above code output in animated gif,




How to remove items in middle of array element?

Copy and paste the below code in notepad and save as index.html .Then open with the browser.
The highlighted yellow color code is the most important part here.We are using same splice but not giving items here. The first value 2 denotes array element here books[2](i.e) maths . The second value 2 denotes how much items going to delete here maths and zoology.


<button onclick="functiontoremoveelement()">Click here to
remove  Array Elements
in Middle For Each Click</button>
<p id="abc"></p>
<script>
var books=['english' , 'science','maths','zoology','botany'];
document.getElementById("abc").innerHTML = books;
function functiontoremoveelement() {
books.splice(2,2 );
document.getElementById("abc").innerHTML =books;
}
</script>
\\
An animated gif explains output of splice remove below,


remove-items-splice-javascript
Print Friendly and PDF
SHARE

About me

Hi. I am interested in blogging.And sometimes play with webdesign,web development,domain sale,designing logo and more.

    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment

Pages