I have an array of point objects with x and y parameters such as :
this.points = [p1, p2, p3,..];
Which I flatten as a 1D array like so :
this.coords = [];
for(let p of this.points){
this.coords.push(p.x);
this.coords.push(p.y);
}
The coords array is now :
this.coords = [p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, ...]
My question is the following, I would like the modifications of either one of the arrays affect the other. Because right now when I make a modification to either this.coords or this.points, the other one isn't updated.
Is there a way of doing this, or am I thinking about this wrong and there is a general guideline to coding coordinates that I do not know of yes ?
Thanks
CodePudding user response:
JavaScript has two kinds of values: reference values and primitive values.
Primitive values, like numbers, are copied and editing the copy never influences the original and the other way around. Because your x and y coordinates are probably primitive numerical values, this is not possible.
You could encapsulate them in reference values, for example using arrays with 1 element.
const points = [{x: [1], y: [2]}, {x: [3], y:[4]}];
const flat = [points[0].x,points[0].y,points[1].x,points[1].y];
flat[0][0] =9;
console.log(points[0].x)
But the question is why you want to do that in the first place. If that is some kind of extreme cache optimization, like making your own commercial game engine, any kind of method to synchronize the two data structures will probably more than neutralize that optimization benefit.
