How to check if an integer include specific digits x times in JavaScript

4 Answers

0 votes
function checkDigitCount(number, digit, count) {
  const regex = new RegExp(digit, 'g');
  const matches = number.toString().match(regex);
  
  return matches && matches.length === count;
}

console.log(checkDigitCount(7097175, '7', 3)); 
console.log(checkDigitCount(70975, '7', 3)); 



/*
run:

true
false

*/

 



answered Apr 27, 2025 by avibootz
0 votes
function checkDigitCount(number, digit, count) {
  const digitArray = number.toString().split('');
  const filteredDigits = digitArray.filter(d => d === digit);
  
  return filteredDigits.length === count;
}

console.log(checkDigitCount(7097175, '7', 3)); 
console.log(checkDigitCount(70975, '7', 3)); 



/*
run:

true
false

*/

 



answered Apr 27, 2025 by avibootz
0 votes
function checkDigitCount(number, digit, count) {
  let digitCount = 0;
  const numStr = number.toString();
  
  for (let i = 0; i < numStr.length; i++) {
    if (numStr[i] === digit) {
      digitCount++;
    }
  }
  
  return digitCount === count;
}

console.log(checkDigitCount(7097175, '7', 3)); 
console.log(checkDigitCount(70975, '7', 3)); 



/*
run:

true
false

*/

 



answered Apr 27, 2025 by avibootz
0 votes
function integerIncludeDigitXTimes(n, xtims, digit) {
    let count = 0;

    // Count occurrences of the digit in the number
    while (n > 0) {
        if (n % 10 === digit) {
            count++;
        }
        n = Math.floor(n / 10); // Perform integer division
    }

    // Return true if count matches xtims
    return count === xtims;
}

console.log(integerIncludeDigitXTimes(7097175, 3, 7)); 
console.log(integerIncludeDigitXTimes(70975, 3, 7));  




/*
run:

true
false

*/

 



answered Apr 27, 2025 by avibootz
...