Tag Archives: javascript array splice

JavaScript Remove Item from Array

Here is my quick and dirty, but good and intuitive, method for deleting an item from an array. The example below is given in a loop and also demonstrates how to build an array and get an array's length. Three in one, you can't loose with this demo!

<!DOCTYPE html>
<html>
<body>

<p>Click the button to remove two elements from the array.</p>

<button onclick="myFunction('Banana')">-Banana</button>
<button onclick="myFunction('Orange')">-Orange</button>
<button onclick="myFunction('Apple')">-Apple</button>
<button onclick="myFunction('Mango')">-Mango</button>

<p id="demo"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction(frt) {
//iterate over array:
for(i=0;i<fruits.length;i++){
    if(fruits[i]==frt){
    fruits.splice(i, 1);
    }
}//end foreach
document.getElementById("demo").innerHTML = fruits;
}
</script>
</body>
</html>

To make the above work, simply save it in a file and call it anything.html and open it in your favorite, javascript enabled, browser such as Firefox. Then click on "-Apple"(minus Apple) and it will remove the Apple. Click on other buttons it will remove the specified item from the array and print the results to the screen for you to confirm.

Note that this demo show you can remove an item from an array by doing this:

fruits.splice(position, number-to-remove);

...where position is the position of the item you wish to start removing items and number-to-remove is the number of items to remove starting at that position. Simple! Play with it and get used to it and it'll make more sense.

Also note that we demonstrated how to build an array like:

var fruits = ["Banana", "Orange", "Apple", "Mango"];

...and we all know that JavaScript uses Objects instead of traditional Arrays like PHP and other languages use, but it's all the same for the purposes of this demo.

One more thing this demo shows people is how to get the number of items of an array or the length of an array in JavaScript. That is accomplished like this:

var arrayLength = fruits.length;

Summary

Ab-a-dee-ab-ah-dee, that's all folks!