What is the best way to get the minimum or maximum value from an Array of numbers?

后端 未结 18 1075
日久生厌
日久生厌 2020-11-27 03:00

Let\'s say I have an Array of numbers: [2,3,3,4,2,2,5,6,7,2]

What is the best way to find the minimum or maximum value in that Array?

Right now,

18条回答
  •  醉酒成梦
    2020-11-27 04:01

    After reading everyone's comments (thank you for your interest), I found that the "best" way (least amount of code, best performing) to do this was to simply sort the Array, and then grab the first value in the Array:

    var myArray:Array /* of Number */ = [2,3,3,4,2,2,5,6,7,2];
    
    myArray.sort(Array.NUMERIC);
    
    var minValue:int = myArray[0];
    

    This also works for an Array of Objects - you simply use the Array.sortOn() function and specify a property:

    // Sample data
    var myArray:Array /* of XML */ = 
        [
        
        
        
        
        
        ]
    
    // Perform a descending sort on the specified attribute in Array to get the maximum value
    myArray.sortOn("@level", Array.DESCENDING | Array.NUMERIC);
    
    var lowestLevel:int = myArray[0].@level;
    

    I hope this helps someone else someday!

提交回复
热议问题