Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

javascript - return largest phone number in JS array

I have to return the largest phone number,not index, from an array in Javascript. I am trying to remove the non digit characters then find largest number. I am new and not experienced with the syntax. Alot of examples show parts of my problem. I don't know how to connect them into one function and how to return the answer. Please help me out. Heres what I have:

function myFunction(array) {
    var largest = array.replace(/D/g, '');
    for (var i = 0; i < array.length; i++) {
        if (largest < array[i]) {
            largest = array[i];
        }
    }
    console.log(largest);
}

myFunction([509 - 111 - 1111, 509 - 222 - 2222, 509 - 333 - 3333]);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As suggested by fellow friends, you need to wrap the phone numbers within quotes as they are not numbers. Once you have done that, try following logic to extract the desired results for you

function myFunction(array) {

  // Creates the number array against the telephone numbers 
  var numberArray = array.map(function(phone){
     return parseInt(phone.replace(/D/g, ''));
  });


  // Now it is simple to compare and find the largest in an array of numbers
  var largestIndex = 0;
  var largestNumber = numberArray[0];

  for (var i = 0; i < numberArray.length; i++) {
     if (largestNumber < numberArray[i]) {
        largestNumber = numberArray[i];
        largestIndex = i;
     }
  }
  // Fetch the value against the largest index from the phone numbers array
  console.log(array[largestIndex]);
}

myFunction(["509 - 111 - 1111", "509 - 222 - 2222", "509 - 333 - 3333", "509 - 333 - 3332"]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...