How to usea Reduce Method in Javascript
In this approach, we are using the reduce function. By converting the number to a string and splitting it into individual digits, the function accumulates the count using the reduce method,
Syntax:
function counting(num) {
return String(num).split('').reduce(
(count, digit) => count + 1, 0);
}
Example: Here, the counting function splits numbers into digits, then reduces the array to count digits.
function counting(num) {
return String(num).split('').reduce(
(count, digit) => count + 1, 0);
}
let num1 = 12345;
let num2 = 987654321;
let result1 = counting(num1);
let result2 = counting(num2);
console.log("Number of digits in " + num1 + ": " + result1);
console.log("Number of digits in " + num2 + ": " + result2);
Output
Number of digits in 12345: 5 Number of digits in 987654321: 9
JavaScript Program to Count Digits of a Given Number
Count Digits of a Given Number refers to determining the total number of individual digits present in a given numerical value. This involves analyzing each digit within the number and calculating how many digits are present in total.
Examples:
Input : 12345 Output : Total number of digits in 12345 is : 5 Input : 64674345 Output : Total number of digits in 12345 is : 8
There are several methods that can be used to Count Digits of a Given Number:
Table of Content
- Using a Reduce Method
- Using for Loop
- Using String Conversion
- Using Math Log10
- Using Recursion
- Using a While Loop and Integer Division
Contact Us