2

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.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • https://stackoverflow.com/questions/13756482/create-copy-of-multi-dimensional-array-not-reference-javascript – epascarello Aug 30 '21 at 20:34
  • 1
    `const segunda = primera.map(pairs => pairs.map(pair => [pair[1], pair[0]]));` –  Aug 30 '21 at 20:34
  • You are not modifying the `newArr` array, you are modifying the `newArr[i]` arrays (which you didn't clone) – Bergi Aug 30 '21 at 20:47

2 Answers2

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)
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
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)
J_K
  • 688
  • 5
  • 12