How to remove or replace array element in JavaScript ?

Published on June 4, 2016 by abundantcode

Filed under JavaScript

Last modified June 4, 2016

Print this page

rate 1 star rate 2 star rate 3 star rate 4 star rate 5 star
Your rating: none, Average: 4.7 (3 votes)

This article have been viewed 5148 times

To remove or replace an element in an array in JavaScript , you can use the splice method as shown below.

How to remove or replace array element in JavaScript ?

To remove the array element , you can use the splice method and specify the index of the array to remove the array element. The second parameter determines the number of elements to remove.

<script type="text/javascript">
    var players = new Array('Sachin Tendulkar', 'Virat Kohli', 'Dhoni');
    players.splice(players.indexOf('Dhoni'),1));
    console.log(players);
</script>

image

 

Replace the array element with another element using the same splice method but pass the third parameter to define the replacement element.

<script type="text/javascript">
    var players = new Array('Sachin Tendulkar', 'Virat Kohli', 'Dhoni');
    players.splice(players.indexOf('Dhoni'), 1,"Ganguly");
    console.log(players);
</script>

image

Leave a Comment


x

You might be Interested in these Posts

C Program to find the G.C.D of a number using Recursive function

Problem Write a program in C to find the find the G.C.D of a number using recursion and display the ...

C Program to print a Half Pyramid using *

Problem Write a program in C to print Half pyramid using * as shown. * * * * * * * * * * ...

C Program to display Positive factors of a number

Problem Write a program in C to display all the positive factors of a number enter by the user. Ho...