Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Write a JavaScript function findLargestBySumOfDigits(arr) that accepts as a parameter an array of numbers
- or/and strings and returns the element with the largest sum of its digits. The function should take
- a variable number of arguments. It should return undefined when 0 arguments are passed or when some
- of the arguments is not an integer number. Write a JS program largestSumOfDigits.js that invokes your function
- with the sample input data below and prints its output at the console. */
- "use strict";
- function findLargestBySumOfDigits(arr) {
- if (!arr.length) {
- return undefined;
- }
- for (var i = 0; i < arr.length; i += 1) {
- if (arr[i] == Number(parseInt(arr[i])) && arr[i] % 1 === 0) arr[i] = parseInt(arr[i]);
- else return undefined;
- }
- var maxSum = 0;
- var indexMax = 0;
- for (i = 0; i < arr.length; i += 1) {
- var number = Math.abs(arr[i]);
- var sum = 0;
- do {
- sum += number % 10;
- number = parseInt(number / 10);
- } while (number);
- if (sum > maxSum) {
- indexMax = i;
- maxSum = sum;
- }
- }
- return arr[indexMax];
- }
- console.log(findLargestBySumOfDigits([5, 10, 15, 111]));
- console.log(findLargestBySumOfDigits([33, 44, -99, 0, 20]));
- console.log(findLargestBySumOfDigits(['hello']));
- console.log(findLargestBySumOfDigits([5, 3.3]));
- console.log(findLargestBySumOfDigits(['32', '149', '-96', '428']));
- console.log(findLargestBySumOfDigits([]));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement