Presented here is an array of objects:
const data = [
{ start: "X", end: "Y", distance: 5},
{ start: "X", end: "Z", distance: 4},
{ start: "Z", end: "Y", distance: 8},
{ start: "Y", end: "V", distance: 9},
{ start: "V", end: "Z", distance: 17},
]
The task at hand is to determine the shortest path based on 'distance' from point X to Y. To achieve this, a 2D distance matrix has been created.
findUniquePoints() {
let _points = []
data.forEach(item => {
if (!_points.includes(item.start)) {
_points.push(item.start)
}
if (!_points.includes(item.end)) {
_points.push(item.end)
}
})
return _points
}
this.pointsArray = this.findUniquePoints()
let _matrix = []
this.pointsArray.forEach((point, index) => {
_matrix[index] = this.pointsArray.map(() => 0)
})
data.forEach(item => {
_matrix[this.pointsArray.indexOf(item.start)][this.pointsArray.indexOf(item.end)] = item.distance
})
console.log(_matrix)
// The log displays the populated matrix:
//[[0, 5, 4, 0][0, 0, 0, 9][0, 8, 0, 0][0, 0, 17, 0]]