Using the djikstra pathfinding-like logic, build a map of steps to each point while keeping track of the path to it:
var obs = [
{ from: "A", to: "C", dis: 5 },
{ from: "A", to: "D", dis: 4 },
{ from: "D", to: "C", dis: 8 },
{ from: "C", to: "B", dis: 9 },
{ from: "B", to: "D", dis: 17 },
];
function findPath(from, to) {
var open = obs
.filter(function (part) {
return part.from == from || part.to == from;
});
var dict = {};
dict[from] = { dis: 0, path: from };
obs
.filter(function (part) {
return part.from == from || part.to == from;
})
.forEach(function (v, i) {
if (dict[v.to] === void 0) {
dict[v.to] = { dis: v.dis, path: from + v.to };
}
else if (dict[v.to].dis > v.dis) {
dict[v.to] = { dis: v.dis, path: from + v.to };
}
});
while (dict[to] === void 0) {
for (var key in dict) {
if (dict.hasOwnProperty(key)) {
var closed = dict[key];
obs
.filter(function (part) {
return part.from == key || part.to == key || part.from == key || part.to == key;
})
.forEach(function (v, i) {
var c = v.dis + closed.dis;
if (dict[v.to] === void 0) {
dict[v.to] = { dis: c, path: closed.path + v.to };
}
else if (dict[v.to].dis > c) {
dict[v.to] = { dis: c, path: closed.path + v.to };
}
if (dict[v.from] === void 0) {
dict[v.from] = { dis: c, path: closed.path + v.to };
}
else if (dict[v.from].dis > c) {
dict[v.from] = { dis: c, path: closed.path + v.to };
}
});
}
}
}
return dict[to];
}
//TEST
var path = findPath("A", "B");
console.log(path);
solved Find shortest path from array of objects in JavaScript