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

459
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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