I have an array of objects that represent the position of div elements on a page. The array is unsorted and I need to sort them so they are arranged in order from left to right and then top to bottom.
The array "items" is:
[{
    "id": "Box 2",
    "x": 354,
    "y": 6
},
{
    "id": "Box 3",
    "x": 15,
    "y": 147
},
{
    "id": "Box 1",
    "x": 12,
    "y": 12
},
{
    "id": "Box 4",
    "x": 315,
    "y": 146
}]
I've tried sorting by both x:
items.sort(function(a, b){
if (a.x == b.x) return a.y - b.y;
    return a.x - b.x || a.y - b.y;
});
and/or sorting by y:
items.sort(function(a, b){
    if (a.y == b.y) return a.x - b.x;
    return a.y - b.y;
});
The items are sorted by x or y respectively, but I want them to be arranged so that the array is sorted box1, box2, box3, box4: