如何生成字符串中每个整数的最大总和的元素?

时间:2016-01-24 06:27:33

标签: javascript arrays

//  Produce the element with largest sum of each integer in the string.
var phoneList1 = ["111-111-1113", "111-111-1113", "111-111-1111", "111-111-1112"];

for (var i = 0; i < phoneList1.length; i++) {           // Iterating through the array
    phoneList1[i] = phoneList1[i].replace(/-/g, '');    // Removing the dashes (-)
    phoneList1[i] = parseInt(phoneList1[i], 10);        // Converting to integers   
}

就我而言。

给定一组电话号码,我如何在列表中找到当字符串中的每个数字加在一起时该项目中列表中所有项目中最大的项目。

示例:"111-111-1111" = 10

2 个答案:

答案 0 :(得分:0)

您打开浏览器的控制台并粘贴以下代码:

&#13;
&#13;
var phoneList1 = ["111-111-1113", "111-111-1113", "111-111-1111", "111-111-1112"];

//this function returns the largest sum
function mainWithTrack(phoneBook){
  //number is a string with integers and dashes(or other chars)
  function convertNumberToInt(number){
    var numberDigits = number.split('');
    var sum = 0;
    numberDigits.forEach(function(number){
       if (parseInt(number)){
         sum += parseInt(number);
       }
    });
    return sum;
  }
  var convertedPhoneBook = phoneBook.map(function(phoneNumber, index){
      return { number: convertNumberToInt(phoneNumber), index: index };
  });
  function compareNumbers(a, b) {
    return a.number - b.number;
  }
  return convertedPhoneBook.sort(compareNumbers)[phoneBook.length-1];
}
//now call it 
var largest = mainWithTrack(phoneList1);
console.log("Largest sum is ", largest.number, " at index ", largest.index, " in phoneList1: ", phoneList1[largest.index]);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

以下适合您的情况:

var pn = [
  0,
  "more invalid numbers",
  "111-111-111",
  "111-111-112",
  "111-111-115",
  "111-711-111",
  "111-111-113",
  1,
  "invalid"
];

// String summing function
function sumPN(s) {
  if (typeof(s) !== "string")
    return 0;
  return s.split("").reduce(function(r, n) {
    // All non-digits are set to 0
    r = parseInt(r);
    n = parseInt(n);
    if (isNaN(r))
      r = 0;
    if (isNaN(n))
      n = 0;
    return r+n;
  });
}

function getLarge(a) {
  var sum = 0;
  return a[a.reduce(function(large, cur, idx) {
    // convert first element
    if (idx === 1) {
      sum = sumPN(large);
      large = 0;
    };

    // parse all the rest, compare, set new index and sum where necessary
    curSum = sumPN(cur);
    console.log(curSum, cur);
    if (curSum > sum) {
      sum = curSum;
      return idx;
    }
    return large
  })];
}
document.write(getLarge(pn));