Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash filter with limit

Is there a way to filter the first n elements from an array that match a criteria?

I know you can filter and then call take but doesn't that go through the whole list instead of exiting after reaching the limit?

_(books).filter(function(book) {return book.pages > 10}).take(5).value();
like image 467
NDavis Avatar asked Dec 06 '25 18:12

NDavis


1 Answers

If the iterator function passed to the _.forEach() function returns false, the iteration is stopped immediately.

The following filter function illustrates how _.forEach() can be used to solve your use case.

function filter(books, maxCount) {
  var results = [];
  _.forEach(books, function(book) {
    if (results.length === maxCount) {
      return false;
    }
    if (book.pages > 10) {
      results.push(book);
    }
  });
  return results;
}


var N = 5;
var books = new Array(20);

// Give each book a page count equal to its books index.
_.forEach(books, function(v, i) {books[i] = {pages: i}});

console.log(filter(books, N));
<script src="https://cdn.jsdelivr.net/lodash/4.15.0/lodash.min.js"></script>
like image 191
cybersam Avatar answered Dec 10 '25 02:12

cybersam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!