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

163
Visualizações
Why do values of an array count down multiple times with this code?

When you use this code

const x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var y = []


x.forEach(elt => {
    for(let i = 0; i < elt; i++){
        y.unshift(i)
    }
})

console.log(y)

it keeps counting down the array 'x' the length of x times. Please explain this to me.

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

0

The code is doing exactly what you're asking it to do.

You are running a for-loop for every element in x.

So you are running

for (let i = 0; i < x[0]; i++) ... //i goes from 0 to 0
for (let i = 0; i < x[1]; i++) ... //i goes from 0 to 1
for (let i = 0; i < x[2]; i++) ... //i goes from 0 to 2
for (let i = 0; i < x[3]; i++) ... //i goes from 0 to 3
...

That's why you're getting those 9...0, 8...0, 7...0, and so on.

const x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let y = []


x.forEach(elt => {
    console.log(`For the element ${elt}`);
    //For each element in x, you are executing the following loop:
    for(let i = 0; i < elt; i++){
        console.log(`unshifting ${i}...`);
        y.unshift(i)
    }
    console.log(`End of each element (${elt}): ${y}`);
})

//if you want each element in x to unshift into y, you need to simply:

const z = [];

x.forEach(elem => z.unshift(elem))
console.log(z);

about 4 years ago · Juan Pablo Isaza Relatório

0

Here is a cleaner way to achieve the same result:

const x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const y = []

x.forEach(n => x.slice(0, n).forEach((_, i) => y.unshift(i)))

Code with explanation:

const x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const y = []

// For each number in x array:
x.forEach(n => 
  // Create a new array from 0 to the current n number:
  // [0, ..., n]
  x.slice(0, n).forEach((_, i) => 
    // And iterate adding the current i index to the beginning of y array
    y.unshift(i)
  )
)

console.log(y)

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