我必须展示一组相互依赖的图像。例如
Image A depends on no one
Image B depends on A
Image C depends on A and B
Image D depends on F
Image E depends on D and C
Image F depends on no one
我有一个像这样的 JavaScript 对象:
const imageDependencies = {
A: [],
B: ['A'],
C: ['A', 'B'],
D: ['F'],
E: ['D', 'C'],
F: []
}
我需要让所有图像名称按其依赖项排序。此示例的结果可能是以下任何一个:
// so first yo get the value of A. Once you have it you can get the value of B. Once you have the value of A and B you can get C, and so on
result_1 = [A, B, C, F, D, E]
// this could be another correct result
result_2 = [A, F, D, B, C, E]
我尝试过使用Array.sort()
像这样的函数:
let names = Object.keys(imageDependencies);
names.sort((a,b) => {
if(imageDependencies [a].includes(b)) return 1
else return -1
})
但工作不正常。
如何才能做到这一点?