knockout.js Remove specific item from all other drop-downs

Current example shows you how to remove selected Items from in one drop down from the other dropdowns

by pkysylevych

HTML

<select data-bind="options: values1, optionsCaption: 'Choose item', value: selected[0]"></select>
<select data-bind="options: values2, optionsCaption: 'Choose item', value: selected[1]"></select>
<select data-bind="options: values3, optionsCaption: 'Choose item', value: selected[2]"></select>

JavaScript

var viewModel = function(data) {
   var self = this;
   this.values = ko.observableArray([ "Item 1", "Item 2", "Item 3"]);
   this.selected = [
       new ko.observable(),
       new ko.observable(),
       new ko.observable()
   ]
   
   this.remaining = function (current) {
       var selected = ko.toJS(self.selected),
           currentValue = ko.utils.unwrapObservable(current);
       var result = ko.utils.arrayFilter(self.values(), function (option) {
           return option == currentValue || selected.indexOf(option) === -1;
       });
       return result;            
   };
     
   this.values1 = ko.computed(function () {
      return self.remaining(self.selected[0]);
   });
   this.values2 = ko.computed(function () {
      return self.remaining(self.selected[1]);
   });
   this.values3 = ko.computed(function () {
      return self.remaining(self.selected[2]);
   });
};

ko.applyBindings(new viewModel());