Javascript 使用阵列的目的地城市

Javascript 使用阵列的目的地城市,javascript,Javascript,我有随机飞行路径,这些阵列可以是有序的,也可以是无序的,我的目标是找到目的地城市 我的输入是路径=[“伦敦”、“纽约”]、[“纽约”、“利马”]、[“利马”、“圣保罗”] 我想要的输出是“圣保罗” 我的第一个嵌套for循环是检查航班是否有起点和终点(因为圣保罗没有终点) 我目前的代码如下: var destCity = function(paths) { let truePath = []; let answer = ""; // finds verified

我有随机飞行路径,这些阵列可以是有序的,也可以是无序的,我的目标是找到目的地城市

我的输入是路径=[“伦敦”、“纽约”]、[“纽约”、“利马”]、[“利马”、“圣保罗”]

我想要的输出是“圣保罗” 我的第一个嵌套for循环是检查航班是否有起点和终点(因为圣保罗没有终点)

我目前的代码如下:

var destCity = function(paths) { 
let truePath = [];
let  answer = "";
    
// finds verified paths first two for loops are to find and compare all trips  starting and and a stopping points and the if statment is there to take the trips that have a starting and stopping point that corispond to another flight and log them into a new array called truePath
for (let i = 0; i < paths.length; i++) {
    for (let j = 0; j< paths[i].length; j++) {
        if (paths[i][1] == paths[j][0]) {
            truePath.push(paths[i][1]);
            //should return [New York, Lima] but only returns [New York]
        return truePath;
        }
    }
}



//tests for destination using verified paths, these for loops are for comparing the truePath array with the final desination of each flight. if the truePath array containes the starting desination of the final desination then then the answer = the final desination   
for (let k = 0; k < paths.length; k++) {
    for (let l = 0; l < paths.length; l++) {
        if (truePath[k] == paths[l][0]) {
            answer = paths[l][1].toString();
            break;
        }
    }

}
    
};
var destCity=函数(路径){
设truePath=[];
让我们回答“”;
//查找已验证的路径循环的前两个是查找并比较所有行程的起始点和停止点,if STATTION用于获取具有起始点和停止点的行程,该起始点和停止点对应于另一个航班,并将其记录到名为truePath的新数组中
for(设i=0;i

当我返回我的truePath/我的验证路径时,我只得到[纽约]。如何让它返回[New York,Lima]或任何有起点和终点的路径?

您可以使用两个循环,一个用于向散列添加值,另一个用于查找未消除的正值

函数查找目标(路径){
const cities={};
用于(路径的常数[出发,到达]){
城市[出发]=(城市[出发]| 0)-1;
城市[到达]=(城市[到达]| 0)+1;
}
返回Object.keys(cities).find(city=>cities[city]==1);
}
console.log(findDestination([“伦敦”、“纽约”]、[“纽约”、“利马”]、[“利马”、“圣保罗”])您需要找到一个目标城市,该城市不存在于任何阵列的起始位置

因此,创建一个所有起源城市的列表。然后
路径
中查找其目标不在原点集中的数组

const path=[[“伦敦”、“纽约”]、[“纽约”、“利马”]、[“利马”、“圣保罗”],
origins=新集合(path.map(p=>p[0]),
output=path.find(p=>!origins.has(p[1]))[1]

console.log(output)
请添加输入和想要的输出。您显示的数组有起点伦敦和终点圣保罗,如果您编写了此代码:您能解释每行的作用吗?(在文章中,不是作为评论)当然也不是“这条线比较了两个数组位置”,而是解释了为什么会有这条线以及它会产生什么结果。