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