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

334
Visualizações
How can I optimize this JS code for Codewars?

The task is:

Given an array of digitals numbers, return a new array of length number containing the last even numbers from the original array (in the same order).

Codewars compiler shows the "Execution Timed Out (12000 ms)" error, though the code is working as intended. Please help to optimize my code, because I can't figure it out myself

My code:

function evenNumbers(array, number) {
  for (let i=0; i < array.length; i++) {
    if (array[i] % 2 != 0) {
      array.splice(i, 1); 
      i -= 1;
    }
  }
  array.splice(0, array.length - number)
  return array;
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You're iterating over the whole array, but you only need to iterate over number elements. For example, given a number of 5, you only need to iterate until you find 5 values fulfilling the condition - you don't want to iterate over all of a 10,000-length array if you don't have to. (Codewars tests often have such huge object structures.)

It also says to return a new array, not modify the existing array.

const evenNumbers = (array, number) => {
  const newArr = [];
  for (let i = array.length - 1; i >= 0 && newArr.length <= number; i--) {
    if (array[i] % 2 === 0) newArr.unshift(array[i]);
  }
  return newArr;
};

console.log(evenNumbers(
  [1, 2, 3, 4, 5, 6, 7, 8],
  3
));

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