JavaScript - summing numbers from strings nested in array

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array that contains some demo credit card numbers like this −

const arr = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978', '4556-4242-9283-2260'];

We have been tasked with creating a function that takes in this array. The function must return the credit card number with the greatest sum of digits.

If two credit card numbers have the same sum, then the last credit card number should be returned by the function.

Example

The code for this will be −

const arr = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978', '4556-4242-9283-2260'];
const findGreatestNumber = (arr) => {
   let n, i = 0, sums;
   sums = [];
   while (i < arr.length) {
      sums.push(sum(arr[i]));
      i++;
   }
   n = sums.lastIndexOf(Math.max.apply(null, sums));
   return arr[n];
}
const sum = (num) => {
   let i, integers, res;
   integers = num.split(/[-]+/g);
   i = 0;
   res = 0;
   while (i < integers.length) {
      res += Number(integers[i]);
      i++;
   }
   return res;
};
console.log(findGreatestNumber(arr));

Output

And the output in the console will be −

4252-278893-7978
raja
Published on 24-Nov-2020 11:06:41
Advertisements