Remove Item from Array using jQuery

Today during my work, I came across a situation where I need to remove items from Array using jQuery. I did it using jQuery and thought of sharing with my you as well.

Earlier I had posted about jQuery solution to Find index of element in array, split an array, combine/join arrays and remove duplicate items from array, And In this post, find how to remove item from array with example.

Below code will remove the item from the array by its value (not by index).

$(document).ready(function(){
    var arr = ["jQuery","JavaScript","HTML","Ajax","Css"];
    var itemtoRemove = "HTML";
    arr.splice($.inArray(itemtoRemove, arr),1);
});?

The above code is using JavaScript splice() method and jQuery.inArray() to find out index of the element. The splice() method adds and/or removes elements to/from an array, and returns the removed element(s) where jQuery.inArray() Search for a specified value within an array and return its index (or -1 if not found).

See result below.

And if you want to remove the items from Array by index only then you don't have to use jQuery.inArray to find the index. You can directly use splice() method and pass the index of the element.

$(document).ready(function(){
    var arr = ["jQuery","JavaScript","HTML","Ajax","Css"];
    var itemtoRemove = "HTML";
    arr.splice(1,1);
});?

The second argument in splice() denotes number of items to be removed. If set to 0, no elements will be removed. If you use arr.splice(1,2) then it will remove 2 items from the array which are at index 1.

See result below.

You can also use splice() method to add items in array. Read more about splice() method here.

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...