Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Array Map unexpectedly changed original array values

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");

enter image description here

like image 442
Vincent Tang Avatar asked Feb 04 '26 23:02

Vincent Tang


1 Answers

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);
like image 88
Phil Avatar answered Feb 06 '26 13:02

Phil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!