Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

82
Visualizações
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

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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]);
  }
}
about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda