如何查找存储在数组中的字符串中的数字总和 [英] How to find sum of numbers in string stored in array
问题描述
我已经想出如何使用一个字符串来计算单个字符串中的数字值。
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..
- 包含函数中所需的所有变量和代码。
- 让该函数接受一个参数,该参数将是一个信用卡号字符串数组。
- 确定每个信用卡号码的总和。
- 确定哪个信用卡号码具有最后一个最大的数字总和。
- 使用return语句以原始形式返回所需的卡号。
- Contain all variables and code needed within a function.
- Have that function take one argument which will be an array of credit card number strings.
- Determine the sum of digits for each credit card number.
- Determine which credit card number has the last largest sum of digits.
- Use a return statement to return the required card number in its’ original form
非常感谢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
.
这篇关于如何查找存储在数组中的字符串中的数字总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!