假设我有一个随机打乱的数组,其中包含不同组别的碎片。例如:
let pieces = [
{
id: "a1",
startNode: 18,
endNode: 42,
},
{
id: "a3",
startNode: 16,
endNode: 30,
},
{
id: "b2",
startNode: 48,
endNode: 65,
},
{
id: "a2",
startNode: 42,
endNode: 16,
},
{
id: "a4",
startNode: 30,
endNode: 31,
},
{
id: "b1",
startNode: 23,
endNode: 48,
},
];
我希望它们以正确的顺序返回为两个数组:
ordered = [
[
{
id: "a1",
startNode: 18,
endNode: 42,
},
{
id: "a2",
startNode: 42,
endNode: 16,
},
{
id: "a3",
startNode: 16,
endNode: 30,
},
{
id: "a4",
startNode: 30,
endNode: 31,
},
],[
{
id: "b1",
startNode: 23,
endNode: 48,
},
{
id: "b2",
startNode: 48,
endNode: 65,
},
]
];
它们按照匹配的起始和结束节点排序,因此"a2"排在"a1"之后,因为它的startNode与"a1"的endNode匹配。 "b1"和"b2"属于另一组,因为它们与任何"a"组没有共享起始或结束节点。id不能用于排序,仅用于澄清此处。
有关如何实现它的任何想法吗?我认为它需要某种递归函数,但我无法完全理解。