How can I do this using Reduce function? [closed]

var ?= '110001'.split("").reverse();
var sum = 0;
for (var i = 0; i < y.length; i++) {
  sum += (y[i] * Math.pow(2, i));



It would be simplest to do

console.log(Array.from('110001').reduce((prev, cur) => prev << 1 | cur));

<< is the left-bitshift operator, which here essentially multiplies by two.

Array.from (if available) is preferable to split. In this case it doesn't matter, but split will fail with surrogate pair characters such as ????, while Array.from will handle them correctly. This could also be written as [...'110001'], which ends up being the same thing.

Of course, you could also just say

parseInt('110001', 2)

check this snippet

var binary = '110001'.split("").reverse();

var sum = binary.reduce(function(previous, current, index) {
  previous = previous + (current * Math.pow(2, index));
  return previous;
}, 0);


Hope it helps


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.