javascriptjqueryalgorithm

jquery: sort 4 points to (top-left, top-right, bottom-right, bottom-left)


given: 2 arrays, each containing the coordinates of 4 points:

point_array_a = [point_a_1_x, point_a_1_y, point_a_2_x, ..., point_a_4_y]
point_array_b = [point_b_1_x, ...                       ..., point_b_4_y]

task:

  1. sort point_array_a such that in the end the points are listed in the following order:

    point_array_a_sorted = [top-left_x, top_left_y, top-right_x, top-right_y, bottom-right_x, bottom_right_y, bottom-left_x, bottom_left_y]
    
  2. sort point_array_b in the same way, such that point_a_k_l corresponds to point_b_k_l like in the beginning.


Solution

  • I'm afraid there is no simple algorithm for this. But the following snippet will do the job (assuming that points with larger y-coordinates lie lower than points with lower y-coordinates):

    var i, points = [], leftX = point_array_a[0], topY = point_array_a[1];
    
    for (i = 0; i < 4; i++)
    {
        leftX = Math.min(leftX, point_array_a[i * 2]);
        topY = Math.min(topY, point_array_b[i * 2]);
        points.push([
                     [point_array_a[i * 2], point_array_a[i * 2 + 1]],
                     [point_array_b[i * 2], point_array_b[i * 2 + 1]]
                    ]);
    }
    
    points.sort(function(first, second){
        if (first[0][0] == leftX)
            return first[0][1] == topY ? -1 : 1;
        if (second[0][0] == leftX)
            return second[0][1] == topY ? 1 : -1;
        return first[0][1] < second[0][1] ? -1 : 1;
    });
    
    var point_array_a_sorted = [], point_array_b_sorted = [];
    
    for (i = 0; i < 4; i++)
    {
        point_array_a_sorted.push(points[i][0][0], points[i][0][1]);
        point_array_b_sorted.push(points[i][1][0], points[i][1][1]);
    }
    

    We leverage the existing Array.sort function by feeding it just the right objects to compare and swap — pairs of points.