remove(function(item) { condition }) Method


Advertisements

Description

The KnockoutJS Observable remove(function(item) { return condition }) method removes the items which are satisfying a condition and returns them as an array.

Syntax

arrayName.remove(function(item) { return condition })

Parameters

This method accepts a parameter in the form of a function having a condition. Items from an array satisfying the mentioned condition are removed.

Example

<!DOCTYPE html>
   <head>
      <title>KnockoutJS ObservableArray function based remove method</title>
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
         type = "text/javascript"></script>
   </head>

   <body>
      <p>Example to demonstrate function based remove() method.</p>
      <button data-bind = "click: removeoncondEmp">Remove on condition</button>
      <p>Array of employees: <span data-bind = "text: empArray()" ></span></p>

      <script>
         function EmployeeModel() {
            this.empName = ko.observable("");
            this.chosenItem = ko.observableArray("");
            this.empArray = ko.observableArray(['Scott','James','Jordan','Lee',
               'RoseMary','Kathie']);

            this.removeoncondEmp = function() {
               alert("This function is removing items whos value is 'James'.");
               this.empArray.remove(function (empName) { return empName === 'James' });  
                  //remove where empName is James
            }
         }

         var em = new EmployeeModel();
         ko.applyBindings(em);
      </script>
      
   </body>
</html>

Output

Let's carry out the following steps to see how the above code works −

  • Save the above code in array-remove-fun.htm file.

  • Open this HTML file in a browser.

  • Click the Remove on condition Button.

knockoutjs_observables.htm
Advertisements