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

187
Visualizações
How can I clone an array with a function without changing the original array in javascript?

I would like to create a copy of an array but switching the position of the most inner arrays. This is the original array:

const primera = [
  [["a","b"],["c","d"]],
  [["a","c"],["b","d"]],
  [["a","d"],["c","b"]]
]

I want to create another an array like this but without modifying the "primera" array:

[
  [["b","a"],["d","c"]],
  [["c","a"],["d","b"]],
  [["d","a"],["b","c"]]
]

I have tried this but when I console.log both arrays, the original array is modified.

const primera = [
  [["a","b"],["c","d"]],
  [["a","c"],["b","d"]],
  [["a","d"],["c","b"]]
]

const doubleRound = (arr) => {
  const newArr = [...arr]
  for(let i=0; i<newArr.length;i++) {
    for(let j=0; j<newArr[i].length;j++) {
      newArr[i][j] = [newArr[i][j][1],newArr[i][j][0]]
    }
  }
  return newArr
}

const segunda = doubleRound(primera)

console.log(primera)
console.log(segunda)

Any idea how can I do it? Thank you.

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

0

[...arr] is just a shallow copy, which means nested array are still passed by reference and if you change one, the clone version also changes.

For a deep copy, you can use JSON.parse(JSON.stringify(arr)). This will create a clone for nested arrays

const primera = [
  [["a","b"],["c","d"]],
  [["a","c"],["b","d"]],
  [["a","d"],["c","b"]]
]

let secundo = JSON.parse(JSON.stringify(primera));

  for(let i = 0; i<secundo.length; i++){
    for(let j=0; j<secundo[i].length; j++){
      [secundo[i][j][0], secundo[i][j][1]] = [secundo[i][j][1], secundo[i][j][0]]
    }
  }

console.log(primera)
console.log(secundo)

about 4 years ago · Juan Pablo Isaza Relatório

0

... does shallow copy. So multi-level arrays (and objects) are not copied deeply.

Here is a possible solution, building up on yours.

Firstly, start with an empty array. And push an empty array for every i. For every j index, push into the child array element again.

No need to think worry about indices error this way.

const primera = [
  [["a","b"],["c","d"]],
  [["a","c"],["b","d"]],
  [["a","d"],["c","b"]]
]

const doubleRound = (arr) => {
  const newArr = [];
  for(let i=0; i<arr.length;i++) {
    newArr.push([]);
    for(let j=0; j<arr[i].length;j++) {
      newArr[i].push([arr[i][j][1],arr[i][j][0]]);
    }
  }
  return newArr
}

const segunda = doubleRound(primera)

console.log(primera)
console.log(segunda)

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