I have figured out how to calculate the value of numbers from a single string, using as an example..
var sum = \"13-2-10-7-3\".split(\'-\').reduce(function(x, y)
You could write a maxBy
function, which takes your function as a parameter for determining the maximum element in the array. This would let you easily adapt your code without much work.
var cards = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978', '4556-4242-9283-2260'];
function maxBy(arr, func) {
return arr.reduce(function(max, val) {
return func(val) >= func(max) ? val : max;
}, arr[0]);
}
function sumCC(card) {
return card.split(/-|/).reduce(function(sum, val) {
return sum + parseInt(val, 10);
}, 0);
}
console.log(maxBy(cards, sumCC));
This is a useful utility function. The Lodash utility library also provides a _.maxBy.