How to find sum of numbers in string stored in array

前端 未结 4 1048
耶瑟儿~
耶瑟儿~ 2021-01-23 22:09

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)         


        
相关标签:
4条回答
  • 2021-01-23 22:45

    Loop over the credit card numbers and check if sum is max store it and continue to loop and store the maximum credit card number and return it:

    function max_credit_sum(arr){
      max = -1
      credit_card = ''
      for(ele of arr){
        numbers = ele.replace(/-/g, '').split('')
        sum = 0
        for(num of numbers){
          sum += parseInt(num)
        }
        if(sum >= max){
          credit_card = ele
          max = sum
        }
      }
     return credit_card
    }
    
    // Test
    arr = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978', '4556-4242-9283-2260'] 
    maximum = max_credit_sum(arr)
    
    0 讨论(0)
  • 2021-01-23 22:50

    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.

    0 讨论(0)
  • 2021-01-23 22:57

    You might get the card with maximum sum like this;

    var cards = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978', '4556-4242-9283-2260'],
     cardSums = cards.map(c => c.split("-").reduce((p,c) => +p + +c)),
      maxCard = cards[cardSums.indexOf(Math.max(...cardSums))];
    console.log(maxCard);

    0 讨论(0)
  • 2021-01-23 22:59

    Its not the most performant, but its simple and quick

           
    var ccs = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978', '4556-4242-9283-2260']
    
    // FSFL = F*Simple For-Loop
    var sum = (a, b) => a + b;
    var largestSum = 0; 
    var largestSumLastIdx = 0;
    for (let i = 0; i < ccs.length; i++) {
       let s = ccs[i].split(/-|/).map(Number).reduce(sum, 0);
       if (s >= largestSum) {
         largestSum = s;
         largestSumLastIdx = i;
       }
    }
    
    console.log("The winner is: " + ccs[largestSumLastIdx])

    0 讨论(0)
提交回复
热议问题