learningjavascriptks learningjavascriptks - 1 month ago 5x
Javascript Question

How to use reduce() method on for loops?

I am trying to write a code that converts a Binary into string, i take solutions step by step, my first step is add charcodes then use fromCharcode, I don't know if this is possible but on this is my code:

function binaryAgent(str) {
var x = str.split(' ').map(function (item) { // split with space
return item.split(''); //split every character
var fg = [];

for(var i=0; i<x.length; i++) {
var f = x[i].reduce(function (toArray,item){
var rightPattern = [128,64,32,16,8,4,2,1]; // i want to create this array on every iteration
var op =rightPattern.shift(); // on every iteration, shift a value from rightPattern, this is for binary pattern
if(item=='1'){ // if item is 1,i think it doesn't matter if it's string or num, I care for 0 and 1 only, push the variable op, shifted from array
return toArray.push(op); // push it on the initial value,
},[]); // []<-- initial array.
return x;

binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");

I checked this with debugger and I have observed that: ON every iteration, my rightPattern array is set to undefined again and reset, I also cannot use push and I have this error, TypeError: Cannot read property 'push' of undefined

on MDN, there is an example using concat() method so i tried to push Array.prototype.reduce()


I'd write your function like this:

function binaryAgent(bin) {
  return bin.split(' ').map(function(bytestr) {
    return String.fromCharCode(parseInt(bytestr, 2));

Converting binary representation into numbers is, well, an old task, and it's already solved for you. Even if you want to write your own implementation for studying purposes, it's better to abstract it (so that you can replace parseInt(bytestr, 2) line - but leave the rest of the code intact.

One possible reduce-using approach (not the most performant, mind you, but employing a pretty common technique):

function parseBinary(str) {
  return str.split('').reduce(function(acc, el) {
    return acc * 2 + +el;
  }, 0);

That is, you don't have any 'pre-filled' arrays of powers of 2; instead your accumulator is multiplied by 2 at each reducer step, adding the current digit. As + operator is overloaded, you should convert the digit operand into a number (the easiest way is applying unary plus - +).