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.
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.
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With