Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't we reassign array values inside forEach? [duplicate]

The problem statement is, i should replace the any digit below 5 with 0 and any digit 5 and above with 1.

I am trying to reassign values, but it is not affecting, Why?

function fakeBinary(n) {
    let numbersArr = n.split('');
    numbersArr.forEach(num => {
        if(Number(num) < 5) {
            num = '0';
        } else if(Number(num) >= 5) {
            num = '1';
        }
    });
    return numbersArr.join('');
}

console.log(fakeBinary('3457'));

I except the output of 0011, but the actual output is 3457.

like image 293
iamPavan Avatar asked Jul 29 '26 00:07

iamPavan


2 Answers

forEach doesn't bring the element's reference for primitive values but rather brings a copy of the value in your case. You can easily access that manually through the index, though:

function fakeBinary(n) {
    let numbersArr = n.split('');
    numbersArr.forEach((num, i) => {
//                          ^--- note that `i` is brought and used below to access the element at index [i].
        if(Number(num) < 5) {
            numbersArr[i] = '0';
        } else if(Number(num) >= 5) {
            numbersArr[i] = '1';
        }
    });
    return numbersArr.join('');
}


console.log(fakeBinary('3457'));

Please note that you may also use other prototypes, I just tried to stay as close as possible to your solution, you may also want to use map or, even (not appropriate, though) reduce or even a regular for loop.

like image 105
briosheje Avatar answered Jul 30 '26 14:07

briosheje


forEach used like that won't do anything - use map instead.

let numbersArr = n.split("").map(num => {
  if (Number(num) > 5) {
    num = "0";
  } else if (Number(num) <= 5) {
    num = "1";
  }
  return num;
});

return numbersArr.join("");

Note that to produce your desired output, you need to change your conditions slightly:

if (Number(num) >= 5) {
  num = "1";
} else {
  num = "0";
}
like image 29
Jack Bashford Avatar answered Jul 30 '26 13:07

Jack Bashford