- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
For 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, odd.
Example
The code for this will be −
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(checkSmallestSum(arr));
Output
And the output in the console will be −
false
Advertisements