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

457
Vistas
Why is this Array.prototype.reduce method not working
function dropElements(arr, func) {
    let output = arr.reduce((acc=[], elem) => {
        if (func(elem)){
            acc.push(arr.slice(arr.indexOf(elem)))
            return acc
        }
    }, [])
    return output
}

let tester = dropElements([1, 2, 3, 4,5,6,3,2,1], function(n) {return n >= 3;})
console.log(tester)

I want it to output [3,4,5,6,3,2,1]. But is printing copies of size decreasing arrays.

The statement of the problem: "Given the array arr, iterate through and remove each element starting from the first element (the 0 index) until the function func returns true when the iterated element is passed through it."

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can use Array#slice along with Array#findIndex to find the first index at which the callback function returns true.

function dropElements(arr, func) {
  const idx = arr.findIndex(func);
  return idx >= 0 ? arr.slice(idx) : [];
}
console.log(dropElements([1, 2, 3, 4, 5, 6, 3, 2, 1], n => n >= 3));

If you specifically want to use Array#reduce, you could use a variable to store whether or not the callback has returned true for any element so far.

function dropElements(arr, func) {
  let found = false;
  return arr.reduce((acc, elem) => {
    found = found || func(elem);
    if (found) acc.push(elem);
    return acc;
  }, []);
}
console.log(dropElements([1, 2, 3, 4, 5, 6, 3, 2, 1], n => n >= 3));

about 4 years ago · Juan Pablo Isaza Denunciar

0

Use the shift method to remove the first element from the array until the array is empty or func(arr[0]) returns a truthy value. This method is inefficient as it could be, but it matches the problem statement. Particularly:

  • It removes each element singularly, rather than all at once.
  • It removes elements while iterating.
  • It operates on the array itself, rather than a copy.

function dropElements(arr, func) {
  while (arr.length > 0 && !func(arr[0])) {
    arr.shift();
  }
  return arr;
}

let tester = dropElements([1, 2, 3, 4,5,6,3,2,1], function(n) {return n >= 3;});
console.log(tester);

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