Home > Blockchain >  How to stop javascript filter function from iteration
How to stop javascript filter function from iteration

Time:10-24

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

CodePudding user response:

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]);
  }
}

CodePudding user response:

If want you want to use methods from Array.prototype and shortcut those, you might use Array.prototype.some

const collection = [];
sortedProducts
.some(function(product,i){
    if(this.length >= limit){
        return 1;
    }
    if(product.name.startsWith(search)){
        this.push(product)
    }
},collection)

I am passing an array as this to some method. You can do this with map, forEach, every etc. as well.

Instead of this.length, you can attach an arbitrary property like this._iteration and increment that etc. Other option is to slice the array like @Majed suggested, or just using good old loop and break from that.

  • Related