简体   繁体   中英

Angular.forEach loop is not working properly

PFB the code of my custom filter where it takes a parameter viewbookoption which is a dropdown value. Based on the dropdown value,the data will be shown in the grid.I implemented forEach loop here but it is not working properly and it keeps traversing the loop and gives me close to 10000 records but actually I have only 10 records which should be displayed in the grid.

Any help in this regard will be much appreciated.

    Controllers.filter('filterUnissued', function() {
     return function(books, viewbookoption) {
       if (viewbookoption == "All Books") {
         return books;
       } else {
         angular.forEach(books, function(book) {
           if (book.issued == false) {
             books.push(book);
           }
        });
      }
      return books;
    }
});

You are pushing elements onto the existing books array. Instead, you should create a new array and push onto that. Like this:

var filteredBooks = []
angular.forEach(books, function(book) {
   if (book.issued == false) {
     filteredBooks.push(book);
   }
});
return filteredBooks;

Or, better, use the Array.filter.prototype method:

return books.filter(function(book) {
  return book.issued === false;
});

(Also, always use === instead of ==, unless you have a very good reason to use ==.)

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