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
JavaScript - summing numbers from strings nested in array
When working with arrays containing string numbers (like credit card numbers), you often need to extract and sum the numeric values. This article shows how to find the string with the greatest sum of digits.
Problem Statement
Given an array of credit card numbers as strings, we need to find the card with the highest sum of digits. If multiple cards have the same sum, return the last one encountered.
const arr = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978', '4556-4242-9283-2260'];
Solution Approach
The solution involves two main steps: extracting numbers from each string and calculating their sum, then finding the string with the maximum sum.
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));
4252-278893-7978
How It Works
The sum() function splits each string by hyphens using regex /[-]+/g, converts each part to a number, and adds them together. The findGreatestNumber() function calculates sums for all strings, finds the maximum using Math.max.apply(), and uses lastIndexOf() to handle duplicate maximum values by returning the last occurrence.
Alternative Approach Using Modern JavaScript
const arr = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978', '4556-4242-9283-2260'];
const findGreatestNumberModern = (arr) => {
const sums = arr.map(str =>
str.split('-').reduce((sum, num) => sum + Number(num), 0)
);
const maxSum = Math.max(...sums);
const lastIndex = sums.lastIndexOf(maxSum);
return arr[lastIndex];
};
console.log(findGreatestNumberModern(arr));
4252-278893-7978
Comparison
| Approach | Code Length | Readability | Performance |
|---|---|---|---|
| Traditional (while loops) | Longer | More verbose | Slightly faster |
| Modern (map/reduce) | Shorter | More readable | Good |
Conclusion
Both approaches effectively solve the problem of finding strings with maximum digit sums. The modern approach using map() and reduce() is more concise and readable, while the traditional approach offers slightly better performance for large datasets.
