user3244544
user3244544

Reputation: 109

ko.utils.arrayFilter not working properly

I am trying to filter an array by omitting users that are already in a previous list:

FullList: Tom, Tim, Jim, Jill
UsersList: Tom, Jill

and with the help of another member I was able to use this array filter but the problem is that the filter result is the same as the usersList: Tom, Jill and i want the filter result to be Tim, Jim

var viewModel = function(data){
    var _self = {};
    var FullUsers = ko.observableArray([]);
    var Users = ko.observableArray([]);

    _self.UsersList = function(data){
        $.each(data, function(index, user) {
           _self.Users.push(new userViewModel(user));
        }
    }

    _self.FullList = function(data){
        $.each(data, function(index, user) {
           _self.FullUsers.push(new userViewModel(user));
        }
    }
    this._FilteredUsers=ko.computed(function() {
      return ko.utils.arrayFilter(_self.FullUsers(), function(item) {
        return ko.utils.arrayIndexOf(_self.Users(), item)<0;
      });
    });
}

I have two different get methods one for getting users and the other for full users - they are both the same the only difference is the id I pass in to one and the other doesn't require a passed id.

View Data-bind

<div data-bind="foreach: _FilteredUsers">
   <span data-bind="text: Name"></span>
</div>

how can i alter the code so my result is Tim, Jim?

Current results based off above code - i get FullUsers including the once I don't want to show. when I flip the Users() and FullUsers() I am only getting Users list

Upvotes: 1

Views: 867

Answers (1)

Michael Dunlap
Michael Dunlap

Reputation: 4310

You'll need to search the Users ObservableArray for a matching item using arrayFirst (returns true if any of the filter function returns true). Since you want users in the full list that are NOT in the normal list, you add a ! to the arrayFirst. If the attribute to filter on is an observable, make sure to add () to the end of the attribute.

this._FilteredUsers=ko.computed(function() {
      return ko.utils.arrayFilter(_self.FullUsers(), function(fuitem) {
        return !ko.utils.arrayFirst(_self.Users(), function(item) {
            return fuitem.Name() === item.Name(); //replace .Name  with the attribute you want to match on
        });
});

Upvotes: 2

Related Questions