Help needed with Map the Debris [Solved]

Help needed with Map the Debris [Solved]
0.0 0

#1

I don’t understand why I can’t push the obj in the newArr like I’m trying to do below.
Could somebody explain this to me, please?


function orbitalPeriod(arr) {
var GM = 398600.4418;
var earthRadius = 6367.4447;
var op = 0;
var obj = {name: “”, orbitalPeriod: 0};
var newArr = [];
//Math.round(2 * Math.PI * Math.sqrt(Math.pow(earthRadius + avgAlt, 3)/GM))

for (var i=0; i<arr.length; i++){
op = (earthRadius+arr[i].avgAlt);
op = Math.pow(op,3);
op = op/GM;
op = (Math.sqrt(op));
op = Math.round(2Math.PIop);
obj.name = arr[i].name;
obj.orbitalPeriod = op;
console.log(‘obj’,obj); // here’s the obj
newArr.push(obj); // I’m trying to push it in a new array

}

return newArr; // but the result is newArr 3 times filled with the moon obj Why?
}

orbitalPeriod([{name: “iss”, avgAlt: 413.6}, {name: “hubble”, avgAlt: 556.7}, {name: “moon”, avgAlt: 378632.553}]);


#2

Dealing with objects can be tricky. For one, obj refers to only one and same object: the object {name: "", orbitalPeriod: 0}. For each pass of the loop, you modify this object (change the value of its name and orbitalPeriod properties), and push a reference to this same object to newArr.

So after the loop, you still have that one object (with the values you assigned to it during the last pass), and three references to that object in the array.

Here’s a fix.

  • Place the declaration of that object inside the for-loop. This will reset its values for every pass.
  • Or better yet, remove obj and push directly to newArr:
newArr.push({
  name: arr[i].name,
  orbitalPeriod: op
});
// you'll have to remove console.log though

#3

Thank you for your explanation. I see it now.
And you are right, solution number two is the better one (also simpler: the simpler the better).