Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Checking digit sum of smallest number in the array in JavaScript
We are required to write a JavaScript function that takes in an array of numbers as the first and the only argument. The function should first pick the smallest number from the array and then calculate the sum of all the digits of the number.
If the digit sum of that number is even, we should return true, false otherwise.
Problem Example
If the input array is:
const arr = [12, 657, 23, 56, 34, 678, 42];
Then the output should be:
const output = false;
Because the smallest number in the array is 12 and its digit sum is 1 + 2 = 3, which is odd.
Solution Approach
We need to break this problem into three steps:
- Find the smallest number in the array
- Calculate the sum of digits of that number
- Check if the digit sum is even or odd
Implementation
const arr = [12, 657, 23, 56, 34, 678, 42];
const addDigits = (num = 1, sum = 0) => {
if(!num){
return sum;
};
return addDigits(Math.floor(num / 10), sum + (num % 10));
};
const findSmallest = (arr = []) => arr.reduce((acc, val) => Math.min(acc, val));
const checkSmallestSum = (arr = []) => {
const smallest = findSmallest(arr);
const smallestSum = addDigits(smallest);
return smallestSum % 2 === 0;
};
console.log("Array:", arr);
console.log("Smallest number:", findSmallest(arr));
console.log("Digit sum:", addDigits(findSmallest(arr)));
console.log("Is digit sum even?", checkSmallestSum(arr));
Array: [12, 657, 23, 56, 34, 678, 42] Smallest number: 12 Digit sum: 3 Is digit sum even? false
How It Works
The addDigits function uses recursion to calculate the sum of digits. It extracts the last digit using modulo 10, adds it to the sum, and recursively processes the remaining digits by dividing by 10.
The findSmallest function uses reduce with Math.min to find the minimum value in the array.
Alternative Approach Using String Conversion
const checkSmallestSumAlternative = (arr = []) => {
const smallest = Math.min(...arr);
const digitSum = smallest.toString()
.split('')
.reduce((sum, digit) => sum + parseInt(digit), 0);
return digitSum % 2 === 0;
};
const testArray = [45, 123, 67, 89, 12];
console.log("Array:", testArray);
console.log("Result:", checkSmallestSumAlternative(testArray));
Array: [45, 123, 67, 89, 12] Result: false
Conclusion
Both approaches effectively solve the problem by finding the smallest number and checking if its digit sum is even. The recursive approach is more mathematical, while the string conversion method is more intuitive and readable.
