my code is as follow
sortedProducts = sortedProducts.filter((product, i) => {
if (i + 1 > limit) {
return false;
}
return product.name.startsWith(search);
});
i want to stop iterating at the index = limit
so i can optimize my function because there is no need for items with index > limit
is there something similar to the word break in this case ?
Thanks in advance
Array#filter runs the callback on every item:
Function is a predicate, to test each element of the array. Return a value that coerces to true to keep the element, or to false otherwise.
Therefore, instead of needlessly iterating over the rest of the items, you can get the subarray first using Array#slice:
sortedProducts = sortedProducts
.slice(0, limit)
.filter(product => product.name.startsWith(search));
Another way to really "break" from the loop:
const arr = [];
for(let i = 0; i < sortedProducts.length; i++) {
if (i + 1 > limit) {
break;
}
if(sortedProducts[i].name.startsWith(search)) {
arr.push(sortedProducts[i]);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With