I can't seem to put this problem together,
Return an array containing all indices that are powers of 2
What I have below so far, I know modulo is probably the wrong operate, but I was trying to make it work. I'm not sure what else to try here.
function secondPower(arr) {
let newarr = [];
for(let i = 0; i < arr.length; i++){
if(arr[i] / (2 ** i) === 1){
newarr.push(i);
}
}
return newarr;
}
[1, 2, 4, 5, 7, 16]
You can use Math.log2 to check whether the number is a power of 2, and Array.every to check whether every item in the array matches a condition:
function isPowerOf2(x) {
return Math.log2(x) % 1 === 0;
}
const arr = [1, 2, 4, 5, 7, 16]
const arr2 = [2, 4, 8]
function isArrAllPowerOf2(arr){
return arr.every(isPowerOf2)
}
console.log(isArrAllPowerOf2(arr))
console.log(isArrAllPowerOf2(arr2))