I am pretty new to the Javascript environment. I think one of the most important ways, in order to be good at it, is practice. So I am trying to create a kind of algorithm that detects the number if it has repeated digits.
The algorithm I trying to create should work like below,
Turn the number into a string to use the string prototype.
Use a split prototype to reach each index that number has for the condition.
If arrays first index === arrays[i+1] it should create new array and push(1), else push(0)
At the end of the algorithm we should multiply each element of the last array.
If result return > 0 , "Its True", else "Its False".
Where is my mistake? Anyone can help me?
Here is my code,
function isRepdigit(num) {
const number = num.toString();
const newArr = number.split(" ");
const bag = new Array();
for (let i = 0; i <= newArr.length; i++) {
//Number -> 334
if (newArr[0] === newArr[i]) {
bag.push(1)
} else {
bag.push(0);
}
}
console.log(bag)
let result = 1;
for (let i = 0; i < bag.length; i++) {
result = result * bag[i];
}
return result > 0 ? true : false;
}
console.log("1234:", isRepdigit(123))
console.log("1223:", isRepdigit(1223))
console.log("3333:", isRepdigit(3333))
.as-console-wrapper { max-height: 100% !important; }
number.split(" ")won't work, since there are no spaces innumber. I think you wantnumber.split(). But you don't need to convert it to an array, you can access characters in a string usingnumber[i]433have repeated digits?333,1111, etc.?Setto make this much simpler...return (new Set(num.toString())).size === 1