I am trying to store all the powerful numbers until 100 (numbers that can be expressed as powers, or more formally, https://en.wikipedia.org/wiki/Powerful_number) into an array, then log (Store) it.
I have created two arrays, one with the description of the power used to arrive there and one just numbers.
The code starts by assuming that no base can be larger than 32, as the square root of 1000 is ~31.6. Then, another loop is formed, to determine the exponent. As 2 to the 10th is larger than 1000, the largest exponent must be less than 10.
The algorithm works, and I was able to remove duplicates.
I tried to print numArr, and it worked flawlessly. All 40 of the powerful numbers less than or equal to 1000 were stored. However, when I try to print the objArr, which is the result array, the array is simply 50 objects of the last iteration of the loop that was less than 1000, 31 squared.
Why is this?
var objArr = [];
var numArr = [];
var tempNum = 0;
var tempObj = {
number: 0,
power: ""
};
function shouldAppend(number) {
if (number > 1000) {
return false
}
return true;
}
// the base of the power
for (var b = 2; b <= 32; b++) {
// the exponent of the power
for (var y = 2; y <= 10; y++) {
// tempNum is the result of the base raised to the exponent
tempNum = Math.pow(b, y);
// checks if "tempNum" is less than 1000
if (shouldAppend(tempNum)) {
// all of the below only exceutes if the tempNum is less or equal to 1000
// sets the temporary object's number property to the temporary number
tempObj.number = tempNum;
// sets the temporary object's power property to the current iterators
tempObj.power = `${b} to the power of ${y}`;
// logs the temporary object
console.log(tempObj);
// pushes the temporary object to the result array
objArr.push(tempObj);
numArr.push(tempNum);
// logs the current result array
console.log(objArr);
}
}
}
tempObjin your code.objArr.push(tempObj)will not copy the object, but just store the reference to that single object. Create a new object from a literal inside your loop whenever you need it.