如何查找存储在数组中的字符串中的数字总和

编程入门 行业动态 更新时间:2024-10-27 16:35:16
本文介绍了如何查找存储在数组中的字符串中的数字总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经想出如何使用一个字符串来计算单个字符串中的数字值。

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.

    更多推荐

    如何查找存储在数组中的字符串中的数字总和

    本文发布于:2023-11-30 12:23:49,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1649936.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:总和   字符串   组中   数字

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!