I made an algorithm to convert a binary number to an integer, the thing is that I made quite a few lines of code, my solution to that problem is this:
const binaryArrayToNumber = arr => {
let contador = 1;
let bin;
let binArr = [];
for(let i = arr.length - 1; i >= 0; i--){
contador = contador * 2;
bin = contador / 2;
if(arr[i] === 1){
binArr.push(bin);
}
}
for(let i = 0; i < binArr.length; i ++){
if(binArr[i] !== 0){
binArr = binArr.reduce((valorAntetior, valorActual) => valorAntetior + valorActual);
return binArr;
} else {
return 0;
}
}
};
But looking at other solutions I discovered this solution:
const binaryArrayToNumber = arr => {
return parseInt(arr.join(""),2);
};
Could someone explain the last solution to me? I can't understand what is the function of that 2, thanks.