Reputation: 948
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
Upvotes: 3
Views: 1927
Reputation: 25890
The most efficient way is to process your arrays as iterables. That way you will always iterate through values only once, while applying any number of operations that you want.
The example below is based on iter-ops library:
import {pipe, filter, take} from 'iter-ops';
// define your sortedProducts, + search + limit here;
const result = pipe(
sortedProducts,
filter(product => product.name.startsWith(search)),
take(limit)
);
console.log([...result]); // prints your found products
Upvotes: 1
Reputation: 6501
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.
Upvotes: 1
Reputation: 28424
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]);
}
}
Upvotes: 2