我有一个 JSON 数组,如下所示我想将我的 JSON 数组排序为 AB、BC、CD、DE!我正在努力实现下面提到的输出!我的价值观实际上是航班起点-目的地!例如 ATL-DXB、DXB-MIA、MIA-MAA!所以没有DA方案!我想以一种方式订购它,如果起点是 ATL,那么订购应该从 ATL-DXB 开始!
function compare(a, b) {
if (b.origin != a.destination) return 1;
return 0;
}
const jsonArray = const jsonArray = [
{
"origin": "MAA",
"destination": "AVG"
},
{
"origin": "ATL",
"destination": "MIA"
},{
"origin": "DXB",
"destination": "MAA"
}, {
"origin": "MIA",
"destination": "DXB"
} ];
var result = jsonArray.sort(compare);
我得到的输出:
[
{ origin: 'MAA', destination: 'AVG' },
{ origin: 'ATL', destination: 'MIA' },
{ origin: 'DXB', destination: 'MAA' },
{ origin: 'MIA', destination: 'DXB' }
]
我想要的输出
[
{ origin: 'ATL', destination: 'MIA' },
{ origin: 'MIA', destination: 'DXB' },
{ origin: 'DXB', destination: 'MAA' },
{ origin: 'MAA', destination: 'AVG' }
]
我认为您想找到第一个起点和最后一个目的地之间的路径。
如果我是对的,你需要两个阶段。首先,找到您的顶级节点,然后根据此重新排序您的节点。
这个解决方案可能不是最有效的解决方案,但这是我想到的第一件事。
const jsonArray = [{
"origin": "MAA",
"destination": "AVG"
},
{
"origin": "ATL",
"destination": "MIA"
},{
"origin": "DXB",
"destination": "MAA"
}, {
"origin": "MIA",
"destination": "DXB"
}];
console.log(sortXY(jsonArray));
function findTop(array) {
let top = array[0];
while (true) {
let temp = array.find(a => a.destination == top.origin);
if (!temp) {
break;
} else {
top = temp;
}
}
return top;
}
function sortXY(array) {
let top = findTop(array);
let newArray = [];
newArray.push(top);
while (true) {
let temp = array.find(a => a.origin == top.destination);
if (!temp) {
break;
} else {
newArray.push(temp);
top = temp;
}
}
return newArray;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句