JavaScript - 按位置排序对象(左、上)

B A*_*ams 2 javascript arrays sorting

我有一个对象数组,表示页面上 div 元素的位置。数组未排序,我需要对它们进行排序,以便它们按从左到右,然后从上到下的顺序排列。

数组“项目”是:

[{
    "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
}]
Run Code Online (Sandbox Code Playgroud)

我试过按 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;
});
Run Code Online (Sandbox Code Playgroud)

和/或按 y 排序:

items.sort(function(a, b){
    if (a.y == b.y) return a.x - b.x;
    return a.y - b.y;
});
Run Code Online (Sandbox Code Playgroud)

这些项目分别按 x 或 y 排序,但我希望它们被排列,以便数组按 box1、box2、box3、box4 排序:

按 x,y 排序

Ziv*_*man 5

我想我现在明白你想要达到的目标,

我不确定 .sort 选项是否可行,我可能错了。

这是可以根据您的需要执行的工作代码,基于双索引比较和标记来标记已添加的框。

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);
Run Code Online (Sandbox Code Playgroud)

小提琴示例