How to remove or replace array element in JavaScript ?


This content was proof-read by Grammarly. You can Try Grammary for FREE

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>
How to remove or replace array element in JavaScript ?

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
Newsletter Signup

Subscribe to our weekly newsletter below and never miss the latest product or an exclusive offer.

Newsletter Signup

Subscribe to our weekly newsletter below and never miss the latest product or an exclusive offer.

%d bloggers like this: