
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sum Numbers from Strings Nested in Array in JavaScript
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
Advertisements