finding quadrant from a array of objects using javascript

后端 未结 1 982
一个人的身影
一个人的身影 2021-01-15 05:43

i have a variable of which is an array of objects ,and each object is having points. the variable is :

var points = [
 {x: 1, y: 1 }, 
 {x: -1, y: 1 }, 
 {x:         


        
相关标签:
1条回答
  • 2021-01-15 06:34

    You could use this:

    function max_from_quadrant( x, y ) {
    
        var max_magnitude = 0;
        var maxIndex = -1;
    
        for ( var i = 0; i < points.length; i++ ) {
    
          var point = points[i];
          if ( point.x*x < 0 || point.y*y < 0 )
              continue; 
    
          var magnitude = point.x*point.x + points.y*point.y;
    
          if ( magnitude > max_magnitude ) {
              max_magnitude = magnitude;
              max_index = i;
          }
    
        }
    
        return max_index > -1 ? points[max_index] : false;
    
    }
    

    Just pass in two number arguments with signs that match the quadrant you want to find the maximum in. For your set of points this gives:

    max_from_quadrant( -1, -1 ) // {x: -3, y: -1}
    max_from_quadrant( -1,  1 ) // {x: -1, y: 11}
    max_from_quadrant(  1, -1 ) // {x:  1, y: -2}
    max_from_quadrant(  1,  1 ) // {x: 10, y:  1}
    
    0 讨论(0)
提交回复
热议问题