I am trying to find the first 100 items in a very large array that match a condition and I'd prefer to end the loop once I've found those 100 for efficiency sake, since the method for matching the items is expensive.
The problem is that doing:
const results = largeArray.filter(item => checkItemValidity(item)).slice(0, 100);
will find all the results in the large array before returning the first 100, which is too wasteful for me.
And doing this:
const results = largeArray.slice(0, 100).filter(item => checkItemValidity(item));
could return less than 100 results.
Please what's the most efficient way of doing this?