How to find first n array items that match a condition without looping through entire array
Rather than putting a conditional and break
inside a for
loop, just add the extra length check in the for
condition itself
const data = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14"],
isValid = n => !(n%2),
res = [],
max = 5;
for (let i = 0; i < data.length && res.length < max; i++) {
isValid(data[i]) && res.push(data[i]);
}
console.log(res)
There are several array methods that will exit early Array.some
, Array.every
, Array.find
, Array.findIndex
You can use them to stop the iteration when you need.
Example using Array.find
const data = [-1,-6,-6,-6,1,-2,2,3,4,-5,5,6,7,-8,8,9,-10,10,11,-1,2,3,4,5,-6,7,8,-9,10,11,];
const first10 = [];
data.find(item => (item > 0 && first10.push(item), first10.length >= 10));
console.log(first10 +"");
You ocul take a generator function and exit of the wanted length is found.
function* getFirst(array, fn, n) {
let i = 0;
while (i < array.length) {
if (fn(array[i])) {
yield array[i];
if (!--n) return;
}
i++;
}
}
const
expFn = x => x % 2 === 0,
array = [2, 4, 5, 1, 3, 7, 9, 10, 6, 0];
console.log(...getFirst(array, expFn, 4));