return largest phone number in JS array

后端 未结 4 1675
孤独总比滥情好
孤独总比滥情好 2020-12-12 06:11

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 e

4条回答
  •  情书的邮戳
    2020-12-12 06:57

    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"]);
    

提交回复
热议问题