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:
Sorted by x,y
I think I understand now what you are trying to achieve,
I am not sure it is possible with .sort option, I might be wrong.
This is working code that will do as you wanted, based on double index compare and flag to mark already added boxes.
var arranged = [];
var items = [{
"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
}]
items.sort(function(a, b) {
//sort by x, secondary by y
return a.x == b.x ? a.y - b.y : a.x - b.x;
});
console.log(items);
for (var i = 0; i < items.length; i++) {
//check if was already added
if (typeof(items[i].wasAdded) == "undefined") {
arranged.push(items[i]);
items[i].wasAdded = "true";
for (j = i + 1; j < items.length; j++) {
if (items[i].y > items[j].y && typeof(items[j].wasAdded) == "undefined") {
arranged.push(items[j]);
items[j].wasAdded = "true";
}
}
}
}
console.log(arranged);
fiddle example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With