Loop not returning result at each iteration

I still don’t know how to apply this in my problem, but thanks for your attempt to help

You already applied it to your problem though. If you want to make changes to an array and keep them separate, then you must make copies of the array. That’s what this line

is explicitly doing, copying the array.

Edit: ahh, do you want to change the last copy? Then you need to copy the last copy you made.

All I want is to push whatever is being console logged into arr, which is [ 'b', 'a', 'c' ] and [ 'b', 'c, 'a' ]

There are two ways to do this - destroying the input array’s original state or preserving it. Either way you need to copy things around.

In the last version you posted, you are copying the original array each time and only making a single change to the original array.

If you want to further change following the last modifications, then you would need to copy the last array you made at the top of the loop iteration.

If you instead are fine with changing the input array, then you can go back to the beginning code and copy right before pushing instead of pushing a reference to the same array.

Either way you have to handle the same fact that future changes to any array are reflected in all references to that array. That’s why you need to copy.

Alright, looks like I’m not gonna get it today :man_bowing:

let arrRef = ['a', 'b', 'c'] // <- original array, every other variable
// that holds this array in fact holds just a reference to that array

let res = [] 

res.push(arrRef); // push ref to arr
res.push(arrRef); // push ref to the same arr
res.push(arrRef); // push another ref to the arr
// res: [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]

arrRef[0] = 'X'
// res: [['X', 'b', 'c'], ['X', 'b', 'c'], ['X', 'b', 'c']]

arrRef[1] = 'Y' 
// res: [['X', 'Y', 'c'], ['X', 'Y', 'c'], ['X', 'Y', 'c']]

// So if you don't want the values in the res to change,
// what should you push in the res?

A copy of arrRef? I still don’t see how to solve this.

1 Like

My answer, so far.

//output should be [‘b’,‘c’,‘a’] and [‘c’,‘a’,‘b’] after all iterations
//before each iteration remove the first element and add it to the end of the array, then, return it.
//it’ll be done as long as the array hasn’t reached its end.

function remove(arg){
//The array to return
let newArr = ;

for(let i = 1; i < arg.length; i++){
//removes the first element of the array
let arrShift = arg.shift(arg[0]);

//add it to the end of the initial array
let reArray = arg.concat(arrShift);

newArr.push(reArray);
arg.push(arrShift);

}
return newArr;
}

console.log(remove([‘a’,‘b’,‘c’]));

I think this needs formatting…

Needs formatting. Don’t know why my code wasn’t formatted.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.