Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - sort objects by position (left, top)

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

like image 214
B Adams Avatar asked Dec 05 '25 10:12

B Adams


1 Answers

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

like image 130
Ziv Weissman Avatar answered Dec 08 '25 00:12

Ziv Weissman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!