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

147
Visualizações
Two dimensional array iteration problem, one ghost element created

I want to create a two dimensional containing arrays of length <=3. This should be dynamically filled with the following function:

  let preppedArray = []
  let currIndex = -1
  let innerIndex = 0
  for (let i = 0; i < props.children.length; i++) {
    if (i%3 === 0) {
      currIndex++
      innerIndex = 0
      preppedArray.push ([currIndex,"dummy"])
      let currElement = props.children[i]
      preppedArray[currIndex][innerIndex] = currElement
    } else{
      innerIndex++
      preppedArray[currIndex][innerIndex] = props.children[i]
    }
  }

Oddly, the following is the output:

Array(3) [ (3) […], (3) […], (2) […] ]
​
0: Array(3) [ {…}, {…}, {…} ]
​​
0: Object { "$$typeof": Symbol("react.element"), type: Card(props)
, key: null, … }
​​
1: Object { "$$typeof": Symbol("react.element"), type: Card(props)
, key: null, … }
​​
2: Object { "$$typeof": Symbol("react.element"), type: Card(props)
, key: null, … }
​​
length: 3
​​
<prototype>: Array []
​
1: Array(3) [ {…}, {…}, {…} ]
​​
0: Object { "$$typeof": Symbol("react.element"), type: Card(props)
, key: null, … }
​​
1: Object { "$$typeof": Symbol("react.element"), type: Card(props)
, key: null, … }
​​
2: Object { "$$typeof": Symbol("react.element"), type: Card(props)
, key: null, … }
​​
length: 3
​​
<prototype>: Array []
​
2: Array [ {…}, "dummy" ]
​​
0: Object { "$$typeof": Symbol("react.element"), type: Card(props)
, key: null, … }
​​
1: "dummy"
​​
length: 2
​​
<prototype>: Array []
​
length: 3
​
<prototype>: Array []

It looks as though the algorithm creates one "ghost" dummy element at the end. However, I do not comprehend why or how to fix it. Many thanks in advance!

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

0

So I found a much easier solution using slice:

  let preppedArray = []
  let currIndex = -1
  for (let i = 0; i < props.children.length; i++) {
    if (i%3 === 0) {
      currIndex++
      preppedArray.push (props.children.slice(i,i+3))
    } 
  }

This creates a two-dimesional array with the desired amount of sub-elements.

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