Wednesday, 11 March 2015

remove object or item from array in javascript and JQuery

you can remove object or item from array in javascript and JQuery by following ways.



Using JQuery

1) filter item from list using map() of jquery

    indexes = $.map(list, function(obj, index) {
        if(obj.name == "Jayesh") {
           return index;
        }
    })
 
    Index = indexes[0];

2) removing item from array 
    list.splice(Index, 1);

Remove Item From Array Using Java Script



var array = [2, 5, 9];
var index = array.indexOf(5);
if (index > -1) {
    array.splice(index, 1);
}


Remove Object From Array Using Java Script


1) create function to find and remove object with particulate attribute and value
  
var removeObjectFromArray = function(arr, attr, value){
    var i = arr.length;
    while(i--){
       if( arr[i]
           && arr[i].hasOwnProperty(attr)
           && (arguments.length > 2 && arr[i][attr] === value ) ){

           arr.splice(i,1);

       }
    }
    return arr;
}



2) Example  of calling above created function

var arr = [{Pid:1,name:'Jayesh'},{Pid:2,name:'Mahesh'},{Pid:3,name:'Dhaval'}];
removeObjectFromArray (arr, 'Pid', 1);
//now new value in array will be  [{Pid:2,name:'Mahesh'},{Pid:3,name:'Dhaval'}]

removeObjectFromArray (arr, 'name', 'Mahesh');
///now new value in array will be [{Pid:3,name:'Dhaval'}]

No comments:

Post a Comment