Remove particular element from JavaScript Array


Remove particular element from JavaScript Array : Sometimes we need to remove particular element from the JavaScript Array. There are many methods to remove the selected element from the JavaScript array.
Here in this tutorial we are going to follow the simplest common used method. We will explain how to remove selected element from JavaScript array with example and online demo.


How to Remove particular element from JavaScript Array?

You can remove the particular element from the JavaScript array simply following the two steps as below –

Step 1

First find the index of the element you want to remove from array.

Remove particular element from JavaScript Array Example :

var array = [1, 7, 10, 11];
var index = array.indexOf(10);

Suppose you want to remove 10 then you can get the index of 10 as above.

Step 2

Now use splice method to remove the element by the index as below-

Remove particular element from JavaScript Array Example :

if (index > -1) {
    array.splice(index, 1);
}

The above exammple first checks that the element exists in array or not. Index is -1 if element is found in array. array.splice(index, 1) will remove one element from the given index.

Complete Example

Remove particular element from JavaScript Array By Index:

<script type='text/javascript'>
function removeElement(){
 var array = [1, 7, 10, 11];
 alert('Array Before Delete = '+array);
 var index = array.indexOf(10);
 if (index > -1) {
    array.splice(index, 1);
}
alert('Array After Delete = '+array);
}
</script>

Try it »

The above exammple will remove the element 10 from the given array. If you run the above example it will produce output something like this –

Remove particular element from JavaScript Array


Advertisements

Add Comment

📖 Read More