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.
[...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)
... 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)