Remove Array items from Array of Objects Using jQuery
- Article
- Comment
During my one of a jQuery Work, I was in need of deleting certain items from an array. There i used to code myself to handle that operations by using JavaScript. Meanwhile one of my developer friend suggested me to use jQuery Splice() method to remove the desired items from the array.
Here is my simple example for jQuery Splice method.
$(document).ready(function(){ // DOM Ready var arr = ["varadha","karthi","mizan","rahman","raja"]; var itemtoRemove = "mizan"; arr.splice($.inArray(itemtoRemove, arr),1); });
You can do the splice option by specifying the position of your desired item. The following example will help you to do this.
$(document).ready(function(){ // DOM Ready var arr = ["varadha","karthi","mizan","rahman","raja"]; arr.splice(3,1); });
This is a simple example working with Slice method, With the same function we are going to deal with Array of Objects.
kv_arr_of_obj = {{name:"varadha", lines:"2,5,10"}, {name:"mizan", lines:"1,19,26,96"}};
Here, we are going to delete our desired objects by using any of the following method,
//first method, also the default one kv_arr_of_obj.shift(); // first element removed //second method kv_arr_of_obj.pop(); // last element removed //third Method kv_arr_of_obj.splice(0,1); // first element removed //fourth Method kv_arr_of_obj = kv_arr_of_obj.slice(2); // second element removed
Slice is the most convinent method for me to perform the remove operations. If you have any doubts and comments regarding the deletion post your comment below.