Tell us what’s happening:
Hi all, I have a question regarding copying array contents. To summarize my issue, I wrote this code, and it does in fact pass the test; however, while the question doesn’t ask you to leave the original array untouched, I figured in a real life situation, it would be best not to alter your original information, in this situation, the parameter: arr. I copied all of the contents from ‘arr’, into a new variable ‘newArr’, using the rest operator. When I console.log both, arr and newArr, before the equation the information is exactly the same (which is what I wanted). Yet, when I console.log both, arr and newArr, right before the return statement, it appears both arrays, arr AND newArr, were changed by the equation. I am confused as to why both got manipulated by the equation. I see in the resolution from FCC they pretty much pushed the new values into a new array, but I assumed copying the information from an old array to a new array, wouldn’t alter the original information.
I apologize if this is confusing, but I just want to ensure I understand how to properly use that operator, and work more efficiently with arrays.
Your code so far
function orbitalPeriod(arr) {
Object.prototype.oribtalPeriod;
var GM = 398600.4418;
var earthRadius = 6367.4447;
var newArr = [...arr];
for (let i = 0; i < newArr.length; i++){
newArr[i].orbitalPeriod = Math.round((2 * Math.PI) * (Math.sqrt((Math.pow(earthRadius + newArr[i].avgAlt, 3))/GM)));
delete newArr[i].avgAlt;
}
return newArr;
}
orbitalPeriod([{name: "iss", avgAlt: 413.6}, {name: "hubble", avgAlt: 556.7}, {name: "moon", avgAlt: 378632.553}]);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/map-the-debris