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

114
Visualizações
Unable to push elements in a new array in javascript

I am writing a very easy function where I am checking the even numbers from an array of integer and adding those even numbers into the new array. But after getting the even numbers from first array when I am trying to push into second array its showing undefined.

const arr = [1,2,3,4,5,6];
const newArr = [];

const loop = () => {
 for (var item of array) {
  if (item % 2 == 0) {
   console.log(item);
   newArr.push(item);
  }
 }
};

console.log(loop());     

Output

2 4 6 undefined

Why new array is showing undefined.

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

0

You can do it simply with forEach.

const arr = [1,2,3,4,5,6];
const newArr = [];


arr.forEach(item => {
  if (item % 2 == 0) {
   newArr.push(item);
  }
})

console.log(newArr);     

about 4 years ago · Juan Pablo Isaza Relatório

0

either return the newArray or execute the loop method and print the new Array.

The reason why you get undefined is because loop is currently a void operator and returning nothing. so if you want the loop method to return the array then the second code sample I showed is the better solution. if you just want to print the array then the first one does the trick.

const arr = [1,2,3,4,5,6];
const newArr = [];


arr.forEach(item => {
  if (item % 2 == 0) {
   newArr.push(item);
  }
})

console.log(newArr); 

or

const arr = [1,2,3,4,5,6];

const loop = () => {
 const newArr = [];
 for (var item of arr) {
  if (item % 2 == 0) {
   console.log(item);
   newArr.push(item);
  }
 }
 return newArr
};
console.log(loop());  

both will work.

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