简体   繁体   中英

Underscore reject Function with IndexOf removes all objects from array

I have a small Angular app that I'm writing that makes use of Underscore to look over each object in an array, and remove the object if it does not match the keyword (user input).

$scope.search = function() {
$scope.posts = _.reject($scope.posts, function(p) {
  var i = 0;
  if ($scope.keywords.indexOf(p.author) < 0 ) {
    i++;
  }
  if ($scope.keywords.indexOf(p.id) < 0 ) {
    i++;
  }
  if(i > 0) {
    return true;
  }
});
};

As you can see I'm setting a counter, and then adding to the counter if the keyword is found in the index, then at the end checking the counter to return true or false to remove the object from the array. $scope.posts is array of objects with my data and $scope.keywords is the user input. I'm wanting to lookup the input from $scope.posts.author object and $scope.posts.id object.

If I remove one of the if statements the function performs as expected: everything not matching the keyword is removed from the array. However, as soon as I add another if statement to the function (as seen in my example above), ALL objects are removed from the array.

It looks to me as though filter might be a better fit here:

$scope.posts = _.filter($scope.posts, function(p) {
  return $scope.keywords.indexOf(p.author) > -1 || $scope.keywords.indexOf(p.id) > -1;
});

Working example: http://jsfiddle.net/4xp3sm10/

Instead of filter or reject it would be even easier to do it the opposite way using _.where

var newArray = _.where($scope.posts, {keyword : $scope.keyword});

There you go, one line.

Edit:

If you are stuck on doing it this way, here's a way you could clean it up a little.

$scope.posts = _.reject($scope.posts, function(p) {
  var check = false;
  if ($scope.keywords.indexOf(p.author) < 0 ) {
    check = true;
  }
  if ($scope.keywords.indexOf(p.id) < 0 ) {
    check = true;
  }
  if(i > 0) {
    return check;
  }
});
};

No need to use an integer like that

Since you are rejecting rows you will want to make sure ALL conditions are true. Your code is just checking for either one to be true.

 $scope.search = function() {
    $scope.posts = _.reject($scope.posts, function(p) {
      return (
           ($scope.keywords.indexOf(p.author) < 0 ) &&
           ($scope.keywords.indexOf(p.id) < 0 ) 
      );
    });
 };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM