function navigate(nmbrInt, roads, from, to) { const getRoad = (from, to, roads) => roads.filter((e) => e.from == from && e.to == to)[0]; const getIntersections = (roads) => roads.reduce((r, e) => r.concat([e.from, e.to]), []).filter((e, i, a) => a.indexOf(e) === i); const permutator = function(inputArr, from, to) { var r = []; var permute = function(arr, memo) { var cur, memo = memo || []; for (var i = 0; i < arr.length; i++) { cur = arr.splice(i, 1); if (arr.length === 0) { var n = memo.concat(cur); if (n.indexOf(from) < n.indexOf(to)) { n = n.slice(n.indexOf(from), n.indexOf(to) + 1); if (n.length > 2) r.push(n); } } permute(arr.slice(), memo.concat(cur)); arr.splice(i, 0, cur[0]); } return r; } var res = permute(inputArr); res.push([from,to]); return res; } if (from == to) return [3]; // ?? Strange Test ?? var possibleways = permutator(getIntersections(roads), from, to); console.log(possibleways.length); var shortestDuration = null, shortestWay = null; possibleways.forEach(function(route) { var roadFails = false; var duration = null; for (j = 0; j < route.length - 1; j++) { if (road = getRoad(route[j], route[j+1], roads)) duration += road.drivingTime; else roadFails = true; } if (!roadFails && duration != null && (shortestDuration === null || shortestDuration > duration)) { shortestDuration = duration; shortestWay = route; } }); return shortestWay; }