I have constructor function that creates an object
I initialize an array called arr1, calling the function to make starting values.
I map over the arr1 to make arr2
But my original arr1 was changed. Why is this? Is it because I'm making async callbacks when initializing array and event-loops?
For reference, I was trying to take ideas from my previous post about canvas here for refactoring
function point(x,y){
return {x,y}
}
arr1 = [point(1,2), point(3,4)];
console.log(arr1, "arr1");
arr2 = arr1.map(b=>{
b.x = b.x+2;
b.y = b.y+2;
return b;
})
console.log(arr1, "arr1");
console.log(arr2, "arr2");

In your map callback, you are directly altering properties of each object (b)...
b.x = b.x+2;
b.y = b.y+2;
What I suspect you're after is something more immutable like
const arr2 = arr1.map(({x, y}) => ({
x: x + 2,
y: y + 2
}))
This will create a new array with +2 values without modifying the original at all.
function point(x,y){
return {x,y}
}
const arr1 = [point(1,2), point(3,4)];
console.log('arr1', arr1);
const arr2 = arr1.map(({x, y}) => ({
x: x + 2,
y: y + 2
}))
console.info('arr1', arr1);
console.info('arr2', arr2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With