I have a loop that switches values at every iteration, and I need the result of that operation to be pushed into the arr array so when I return it the result should be [ [ 'b', 'a', 'c' ], [ 'b', 'c', 'a' ] ] but instead it’s returning [ [ 'b', 'c', 'a' ], [ 'b', 'c', 'a' ] ] even though when I console log arg within the loop it returns the expected result. What gives?
function test(arg) {
let arr = []
for (let i = 0; i < 2; i++) {
let savedValue = arg[i]
arg[i] = arg[i + 1]
arg[i + 1] = savedValue
console.log(arg)
arr.push(arg)
}
return arr
}
console.log(test(['a', 'b', 'c']))
let a = [1, 3, 4]
let b = a
b[0] = 100
console.log(a) // [100, 3, 4]
When you assign or pass an array as an argument you don’t make a copy of the array, you pass a reference to the existing instance. So you’re changing in your example the same array and push the reference to the same array in the resulting array.
I know how to make a copy. Can you show me how to achieve what I’m looking for? It’s still returning [ [ 'b', 'c', 'a' ], [ 'b', 'c', 'a' ] ] when I iterate over the copy.
Can you show us what you have tried to change? You stated you now know how to make a copy. @udaaff already gave you example code of how to make a shallow copy. It may be you have the syntax incorrect.
We teach users here to learn to code. All we ask is that a user attempts to code and show us the code when stuck. Then, we can help guide the user to a working solution.
Yes, you made a shallow copy of arg, but where you made it results in the same problem you already had. If you read over @udaaff’s suggestion above about where you should make the copy, you should be able to get it right.
You can use your original code and make the copy of arg (which has all the swapping) as part of the push or you could create a new variable containing the copied arg and push that instead. It is up to you.
With all due respect this is not productive at all and doesn’t achieve anything other than a waste of time on something that can be explained in one post. You don’t even need to explain as I will observe the code and make my conclusions about it, and thus I would have learned something new without going back and forth on something so simple.
You learn far less than you expect from reading somebody else’s code. It is a tempting trap, but reading somebody else’s code is a different (important but different) skill from writing and debugging code.