簡體   English   中英

如何通過坐標 position 和顏色對對象數組進行排序?

[英]How can I sort an array of objects by coordinate position and color?

有一組對象(圖中的數字)具有 position 和顏色。 並且需要從上到下(按Y)得到一個按顏色排序的新數組。 如果在{blueF, yellowF, whiteF, yellowF, YellowF, blueF, blackF}和之后: {blueF, blueF, yellowF, yellowF, YellowF, whiteF, blackF}並且嘗試使用reduce sort時我很痛苦。 但我意識到我需要兩個功能。 一個將返回頂部顏色的 position 數組。 我將對第二個進行排序。 換句話說,我明白了。 但是還沒有關於如何發布它的想法

const Nodes = [{
    type: "triangle",
    position: {
      x: 10,
      y: 15
    },
    color: "yellow"
  },
  {
    type: "square",
    position: {
      x: 20,
      y: 55
    },
    color: "yellow"
  },
  {
    type: "square",
    position: {
      x: 30,
      y: 25
    },
    color: "blue"
  },
  {
    type: "triangle",
    position: {
      x: 40,
      y: 45
    },
    color: "yellow"
  },
  {
    type: "circle",
    position: {
      x: 10,
      y: 55
    },
    color: "blue"
  },
  {
    type: "circle",
    position: {
      x: 20,
      y: 35
    },
    color: "green"
  }
];
console.log(Nodes.sort((a, b) => (a.position.y > b.position.y ? 1 : -1)));

好的,我想我得到了你現在想要做的事情:

這將是我的想法:

const colors = [];

// This will push the colors into the array according to their order (in the y direction)
Nodes
    .sort((a, b) => a.position.y - b.position.y)
    .forEach(n => !colors.includes(n.color) && colors.push(n.color));


// This will sort all the nodes by their color and then their position
Nodes.sort((a, b) => {
    let iA = colors.findIndex(c => c === a.color);
    let iB = colors.findIndex(c => c === b.color);

    return iA === iB ? a.position.y - b.position.y : iA - iB;
});

這將首先按所有節點的位置對所有節點進行排序,以便它可以得到 colors 出現的順序(從上到下)。 之后它將按顏色和 position 對所有節點進行排序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM