How to remove item from array knockout

11,823

The arrayRemoveItem takes the items to be removed as the second argument like ko.utils.arrayRemoveItem(array, itemToRemove), so you need to first find the object and pass it to arrayRemoveItem.

Try

function VM()
{
  this.Items = [{id:'1', name:'A'}, 
                {id:'2', name:'B'}, 
                {id:'3', name:'C'}, 
                {id:'4', name:'D'}
               ];

  this.Delete = function(){

    var item;
    ko.utils.arrayForEach(this.Items, function(v) {
      if(v.id == '3'){
        item = v;
      }
    });

    console.log(this.Items);
    ko.utils.arrayRemoveItem(this.Items, item);
    console.log(this.Items);
  };
}

ko.applyBindings(new VM());

Demo: Fiddle

Share:
11,823
user1740381
Author by

user1740381

Updated on June 26, 2022

Comments

  • user1740381
    user1740381 almost 2 years

    I am using knockout.js library. I am trying to using knockout arrayRemoveItem utility function but it seems that its not working. Here is my code :

    JS

    function VM()
    {
      this.Items = [{id:'1', name:'A'}, 
                    {id:'2', name:'B'}, 
                    {id:'3', name:'C'}, 
                    {id:'4', name:'D'}
                   ];
    
      this.Delete = function(){
        console.log(this.Items);          //before removing
    
        ko.utils.arrayRemoveItem(this.Items, function(item){
          return item.id == '3';
        });
    
        console.log(this.Items);          //after removing
      };
    }
    

    Fiddle

    If you check the console after pressing delete button, item 3 is not removing from array. What i am missing here?

  • Wes Grant
    Wes Grant almost 10 years
    This removed the item from the array for me, but it did not trigger the observable, when I changed the arrayRemoveItem to the remove function on the array, self.availableSecondScreens.remove(itemToDelete) - the observable was triggered
  • Ian
    Ian about 8 years
    Trying arrayRemoveItem and .remove still leaves a blank row in my table.