Javascript从嵌套在数组中的字符串求和数字

时间:2016-12-05 20:55:50

标签: javascript arrays nested sum

我的任务是创建一个具有输入的单个参数的函数。此参数是一个包含包含连字符的信用卡号字符串的数组。 该功能必须输出具有最大数字位数的信用卡号。如果两个信用卡号码具有相同的金额,则应返回最后一个信用卡号。 以下是嵌套数组的示例。

['4916-2600-1804-0530','4779-252888-3972','4252-278893-7978','4556-4242-9283-2260']

以下是我的尝试。任何和所有建议都表示赞赏。谢谢!

function creditSum(creditCardNumber) {
      var number1= creditCardNumber[0];
      var number2= creditCardNumber[1];
      var number3= creditCardNumber[2];
      var number4= creditCardNumber[3];
      var split1=[];
      var split2=[];
      var split3=[];
      var split4=[];
       split1= number1.split ('');
       split2= number2.split ('');
       split3= number3.split ('');
       split4= number4.split ('');
      var sum1= split1[0]+split1[1]+split1[2]+split1[3]+split1[5]+split1[6]+split1[7]+split1[8]+split1[10]+split1[11]+split1[12]+split1[13]+split1[15]+split1[16]+split1[17]+split1[18];
      var sum2= split2[0]+split2[1]+split2[2]+split2[3]+split2[5]+split2[6]+split2[7]+split2[8]+split2[10]+split2[11]+split2[12]+split2[13]+split2[15]+split2[16]+split2[17]+split2[18];
      var sum3= split3[0]+split3[1]+split3[2]+split3[3]+split3[5]+split3[6]+split3[7]+split3[8]+split3[10]+split3[11]+split3[12]+split3[13]+split3[15]+split3[16]+split3[17]+split3[18];
      var sum4= split4[0]+split4[1]+split4[2]+split4[3]+split4[5]+split4[6]+split4[7]+split4[8]+split4[10]+split4[11]+split4[12]+split4[13]+split4[15]+split4[16]+split4[17]+split4[18];
      if (sum1>sum2 && sum1>sum3 && sum1>sum4){
        answer= number1;
      }
      else if (sum2>sum1 && sum2>sum3 && sum2>sum4){
        answer= number2;
      }
      else if (sum3>sum1 && sum3>sum2 && sum3>sum4){
        answer=number3;
      }
      else if (sum4>sum1 && sum4>sum2 && sum4>sum3){
        answer=number4;
      }
      else if (sum1==sum2){
        answer=number2;
      }
        else if (sum1==sum3){
          answer=sum3;
        }
        else if (sum1==sum4){
          answer=sum4;
        }
        else if (sum2==sum3){
          answer=sum3;
        }
        else if (sum2==sum4){
          answer=sum4;
        }
        else if (sum3==sum4){
          answer=sum4;
        }
        return answer

    }

8 个答案:

答案 0 :(得分:2)

您可以使用此ES6功能:

function cardWithMaxSum(creditCardNumbers) {
    return creditCardNumbers.reduce( (best, card) => {
        let sum = card.match(/\d/g).reduce( (a,b) => +a + +b );
        return sum >= best[0] ? [sum, card] : best;
    }, [-1] )[1];
}

var creditCardNumbers = ['4916-2600-1804-0530', '4779-252888-3972', 
                         '4252-278893-7978', '4556-4242-9283-2260'];

console.log(cardWithMaxSum(creditCardNumbers));

答案 1 :(得分:0)

这个问题听起来很像家庭作业。不管怎样,请不要复制& amp;粘贴此代码。阅读评论,花点时间了解它的作用,也许还要研究Array.prototype.sort



//Some sample data
var numbers = [
  "2345-6789-0123-4567",
  "3456-7890-1234-5678",
  "4567-8901-2345-6789",
  "1234-5678-9012-3456"
];

function getLargestCreditNumber(numbers){
  /*
  Custom sort function to sort the array (smallest to largest).
  Sort function runs in iterations and compares two items from the array
  at a time. We need to return 1 if a > b, -1 if a < b, or 0 if they are
  equal.
  */
  numbers.sort(function(a, b){
    //Split number 'a' by hyphens
    var parts1 = a.split('-');
    //Sum the parts
    var sum1 = parts1.reduce(function(a, b){
       return parseInt(a) + parseInt(b);
    }, 0);
    //Split number 'b' by hyphens
    var parts2 = b.split('-');
    //Sum the parts
    var sum2 = parts2.reduce(function(a, b){
       return parseInt(a) + parseInt(b);
    }, 0);
    //Return number to indicate how these two items compare
    return sum1 > sum2 ? 1 : sum1 < sum2 ? -1 : 0;
  });
  //Return the last item in the array
  return numbers.pop();
}
console.log(getLargestCreditNumber(numbers));
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您是否正在寻找最大数字位数的卡号索引?

试试这个:(ES6)

numbers=['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978', '4556-4242-9283-2260']


console.log(
        numbers.map(
                e=>{
                    var value = parseInt(e.replace(new RegExp('-', 'g'),"")),sum = 0;
                    console.log(value);
                    while (value) {
                        sum += value % 10;
                        value = Math.floor(value / 10)
                    }
                    console.log(sum);
                    return sum;
                }
        ).reduce((max, x, i, arr) => x > arr[max] ? i : max, 0)
);

答案 3 :(得分:0)

您可以使用reduceMath.max来大大简化您的代码。像这样:

&#13;
&#13;
const input = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978', '4556-4242-9283-2260'];

function sumDigits(str) {
	return Array.from(str).reduce((result, value) => {
		const num = parseInt(value) || 0;
		return result + num;
	}, 0);
}

function findMax(inputArr) {
	return inputArr.reduce(
		(prev, input) => Math.max(prev, sumDigits(input)),
		0
	);
}

console.log(findMax(input));
&#13;
&#13;
&#13;

答案 4 :(得分:0)

可能类似于这里的许多其他精彩答案

var creditCardsArr = ['4916-2600-1804-0530', 
                      '4779-252888-3972', 
                      '4252-278893-7978', 
                      '4556-4242-9283-2260'];

// Strip off dashes and convert from string to sum of digits of each card
var creditCardSumOfDigitsArr = creditCardsArr.map(function(cc){
  cc = cc.replace(/-/g, "");
  return cc.split("").reduce(function(a, b){ return a + parseInt(b)}, 0);
});

var indexOfMaxCreditCard =   creditCardSumOfDigitsArr.reduce(function(maxIndexSoFar, cur, curIndex, arr){
  return cur >= arr[maxIndexSoFar] ? curIndex : maxIndexSoFar;
}, 0);

console.log("Credit card with highest sum of digits: " +   creditCardsArr[indexOfMaxCreditCard]);

答案 5 :(得分:0)

您可以使用总和的值映射数字,然后选择最后一个最大的对象,只取数字。

&#13;
&#13;
function getMax(array) {
    return array.map(function (a) {
        return { n: a, v: a.match(/\d/g).reduce(function (a, b) { return +a + +b; }) };
    }).reduce(function (r, a, i) {
        return i && r.v > a.v ? r : a;
    }, 0).n;
}

console.log(getMax(['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978', '4556-4242-9283-2260']));
&#13;
&#13;
&#13;

答案 6 :(得分:0)

看,我希望这段代码能够提供帮助,请务必对其进行测试。

function getMaxSerialNumb(sNumbers) {
	/*Function that gets the maximun sum of the
	serial number in a list of serials numbers*/
    var n, i, sums;
    i = 0;
    sums = [];
    while (i < sNumbers.length) {
        sums.push(serialSum(sNumbers[i]));
        i++;
    }
    n = sums.lastIndexOf(Math.max.apply(null, sums));
    return sNumbers[n];
}

function serialSum(sNumber) {
	/*Function that gets the sum of a single 
	serial number.*/
    var i, integers, answer;
    integers = sNumber.split(/[-]+/g);
    i = 0;
    answer = 0;
    while (i < integers.length) {
        answer += Number(integers[i]);
        i++;
    }
    return answer;
}
/*Example*/
numbers=['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978', '4556-4242-9283-2260']
console.log(getMaxSerialNumb(numbers))

答案 7 :(得分:0)

我想按照以下方式完成这项工作;

&#13;
&#13;
library(quantmod)
getSymbols("GOOG")
GOOG2 <- GOOG["2016"]
# Add a column just to demonstrate the values obtained from .indexweek in printed output below. This is just optional.
GOOG2$weeknum <- .indexweek(GOOG2016)

head(GOOG2, 15)
# GOOG.Open GOOG.High GOOG.Low GOOG.Close GOOG.Volume GOOG.Adjusted weeknum
# 2016-01-04    743.00   744.060  731.258     741.84     3272800        741.84    2401
# 2016-01-05    746.45   752.000  738.640     742.58     1950700        742.58    2401
# 2016-01-06    730.00   747.180  728.920     743.62     1947000        743.62    2401
# 2016-01-07    730.31   738.500  719.060     726.39     2963700        726.39    2401
# 2016-01-08    731.45   733.230  713.000     714.47     2450900        714.47    2401
# 2016-01-11    716.61   718.855  703.540     716.03     2090600        716.03    2402
# 2016-01-12    721.68   728.750  717.317     726.07     2024500        726.07    2402
# 2016-01-13    730.85   734.740  698.610     700.56     2501700        700.56    2402
# 2016-01-14    705.38   721.925  689.100     714.72     2225800        714.72    2402
# 2016-01-15    692.29   706.740  685.370     694.45     3592400        694.45    2402
# 2016-01-19    703.30   709.980  693.410     701.79     2268100        701.79    2403
# 2016-01-20    688.61   706.850  673.260     698.45     3445000        698.45    2403
# 2016-01-21    702.18   719.190  694.460     706.59     2412200        706.59    2403
# 2016-01-22    723.60   728.130  720.121     725.25     2011800        725.25    2403
# 2016-01-25    723.58   729.680  710.010     711.67     1711700        711.67    2404

# Subset the second week
GOOG2016[.indexweek(GOOG2016) == 2402,]
# GOOG.Open GOOG.High GOOG.Low GOOG.Close GOOG.Volume GOOG.Adjusted
# 2016-01-11    716.61   718.855  703.540     716.03     2090600        716.03
# 2016-01-12    721.68   728.750  717.317     726.07     2024500        726.07
# 2016-01-13    730.85   734.740  698.610     700.56     2501700        700.56
# 2016-01-14    705.38   721.925  689.100     714.72     2225800        714.72
# 2016-01-15    692.29   706.740  685.370     694.45     3592400        694.45
&#13;
&#13;
&#13;