Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

81
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda