Add or delete elements from Javascript array

Created by
Wednesday, August 10, 2016

Adding and removing elements in an array will be the first basic step that every beginner will be trying to implement in any programming language. Java script has this function to add elements at the beginning of the array and at the end of the array. Similarly, deleting elements is also possible from both the ends of the array.

Pop and push

Both pop and push add and remove elements from the array where the index value is highest. In other words pop and push will affect the last element of the array.

push()

This function will add elements to the end of an array. In the example below pineapple will be added in last position after kiwi.

 

<script type="text/javascript">

var fruit=["apple", "banana","Kiwi"];

fruit.push("pineapple");

</script>

 

The result of this code while printing fruit array will be apple, banana, kiwi, pineapple.

 

Pop()

This function pop will remove the last element from the array and returns the value.

<script type="text/javascript">

var fruit=["apple", "banana","Kiwi"];

fruit.pop();

</script>

Unshift  and shift:

Both these  functions unshift and shift add and remove elements from the array where the index value is lowest. In other words unshift and shift will affect the first element of the array. 

unshift()

This function will add elements to the end of an array. Here in the example below pineapple will be added in last position after kiwi.

<script type="text/javascript">

var fruit=["apple", "banana","Kiwi"];

fruit. unshift ("pineapple");

fruit. unshift ("jackfruit");

</script>

 

Result of this code while printing fruit array will be jackfruit, pineapple, apple, banana, kiwi. Note that if unshift is called twice the last inserted element comes to the index in array.

 

shift()

This function shift will remove the last element from the array and returns the value.

 

<script type="text/javascript">

var fruit=["apple", "banana","Kiwi"];

fruit.shift();

</script>

The result of the code while fruit is printed will be banana, kiwi. The first element apple will be removed and while the code fruit.shift() is printed it will display apple.

Push and unshift works in the same way, inserts elements in an array. The only difference is the position where the element is inserted. Push inserts at the very end while unshift inserts at the beginning.

Same way pop and shift works in the similar way removing elements from an array, removing from different ends of the array.

When you require undo and redo functionality these four functions will come handy.  All these four functions affect the index of the array.

0
Rating
1 2 3 4 5

Save

Saved

Report

Reported
Reasons
Cancel
0 comments