Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop javascript filter function from iteration

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

like image 369
mod7ex Avatar asked Nov 16 '25 00:11

mod7ex


1 Answers

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]);
  }
}
like image 118
Majed Badawi Avatar answered Nov 18 '25 13:11

Majed Badawi



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!