I'm struggling with a javascript issue that may be due to my lack of experience in the language, but I haven't been able to find a solution yet.
The problem is that I need to create a copy array of an array of objects, modify the data in the copy array without affecting the values in the original array of objects, and then reassign the copy array back to the original one so I can use it again with the initial values in another function.
In a simple program I created, there are two classes - Country which has some properties and a method to update one of these properties, and World which contains an array of countries and a function to update the data for all countries in the array. After calling the changeAllCountriesData function on a World instance, both the countries array and the copyData array have changed unexpectedly.
class Country{
name; area; population;
constructor(name, area, population){
this.name = name;
this.area = area;
this.population = population;
}
changeData(){
this.population += Math.round(this.population * 0.02);
}
}
class World{
countries = [];
copyData = [];
constructor(){
this.loadData();
this.copyData = this.countries.slice(0);
}
// Rest of the JavaScript code omitted for brevity
I tried different methods to create the copy array like using spread operator, Array.from(), or Object.assign(), but none of them worked as expected and resulted in unexpected changes to the initial array or NaN values after calculations.