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; }
Advertisement
Answer
The problem is your call to num.split(" ")
. It’s splitting the string at space characters, but there are no spaces between the digits. Use num.split("")
to turn each character into an array element.
But you don’t need to change it to an array, because you can index strings the same way as arrays.
You have another error that’s common among beginners: i <= newArray.length
needs to use <
, not <=
.
function isRepdigit(num) { const number = num.toString(); const bag = []; for (let i = 0; i < number.length; i++) { //Number -> 334 if (number[0] === number[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; }
But your entire algorithm is poor. There’s no need to make an array of all the comparisons. You can simply return false
as soon as you find a character that doesn’t match.
function isRepdigit(num) { const number = num.toString(); for (let i = 1; i < number.length; i++) { if (number[0] !== number[i]) { return false; } } return true; } console.log("1234:", isRepdigit(123)) console.log("1223:", isRepdigit(1223)) console.log("3333:", isRepdigit(3333))
.as-console-wrapper { max-height: 100% !important; }
See also Function that checks whether all characters in a string are equal javascript – Homework Warning