return largest phone number in JS array

后端 未结 4 1670
孤独总比滥情好
孤独总比滥情好 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 07:01

    If you want to use some built in JavaScript functions then you can use the map method of arrays to modify each element of the array, and the Math.max method to find the largest number.

    function myFunction(array) {
        var array = array.map(function(elementOfArrayAtIndex) {
            return parseInt(elementOfArrayAtIndex.replace(/\D/g, ''), 10);
        });
        var largest = Math.max.apply(null, array);
        console.log(largest);
    }
    
    myFunction(["509 - 111 - 1111", "509 - 222 - 2222", "509 - 333 - 3333"]);
    

    Here's a fiddle http://jsfiddle.net/v3b7gx6L/1/

    This is basically what the map method is doing

    for(var j = 0; j < array.length; j++) {
      array[j] = array[j].replace(/\D/g, '');  
    }
    

提交回复
热议问题