我已经想出如何使用一个字符串来计算单个字符串中的数字值。
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) { return parseInt(x)+ parseInt(y); }); // Value of 35我有兴趣找到其数字总和为最大数字的信用卡号码。如果不止一个具有相同的最大数字总和,我们希望列表中的最后一个具有该总和。
Im interested in finding the credit card number whose digits sum to the largest number. If more than one has the same largest sum of digits, we want the last one in the list with that sum.
以下是信用卡号的示例数组:
Here is a sample array of credit card numbers:
['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978', '4556-4242-9283-2260']在上面的示例数组中,数字加起来分别为49,81,81和64。由于有两个具有相同的总和,函数应返回具有该总和的最后一个,在这种情况下'4252-278893-7978'
In the sample array above, the digits add up to 49, 81, 81, and 64 respectively. Since there are two which have the same sum, the function should return the last one with that sum, in this case '4252-278893-7978'
我一直在试图弄清楚如何将其应用于一系列数字..
I am stuck trying to figure out how to now apply this to an array of numbers..
非常感谢Insight
Insight would be much appreciated
推荐答案您可以编写一个 maxBy 函数,该函数将您的函数作为参数来确定数组中的最大元素。这可以让您轻松调整代码而无需太多工作。
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));
这是一个有用的实用功能。 Lodash实用程序库还提供 _。maxBy 。
This is a useful utility function. The Lodash utility library also provides a _.maxBy.
更多推荐
如何查找存储在数组中的字符串中的数字总和
发布评论