JavaScript-根据依赖关系树排序 [英] JavaScript - Sort depending on dependency tree
问题描述
我必须显示一组相互依赖的图像.例如
I must show a set of images that depend on each other. For example
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对象:
I have a javascript object like this:
const imageDependencies = {
A: [],
B: ['A'],
C: ['A', 'B'],
D: ['F'],
E: ['D', 'C'],
F: []
}
我需要让我所有的图像名称按其依赖关系排序.该示例的结果可能是以下任何一个:
I need to get all my image names ordered by their dependencies. The result of this example could be any of these:
// 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()
函数,如下所示:
I've tried using the Array.sort()
function like this:
let names = Object.keys(imageDependencies);
names.sort((a,b) => {
if(imageDependencies [a].includes(b)) return 1
else return -1
})
但是不能正常工作.
这怎么办?
推荐答案
You coult take a Set
for added keys and check if the actual dependency has all elements added to the set. Then add this key, otherwise go on. Proceed until no more items are in the array.
var dependencies = { A: [], B: ['A'], C: ['A', 'B'], D: ['F'], E: ['D', 'C'], F: [], G: ['H'], H: ['G'] },
keys = Object.keys(dependencies),
used = new Set,
result = [],
i, item, length;
do {
length = keys.length;
i = 0;
while (i < keys.length) {
if (dependencies[keys[i]].every(Set.prototype.has, used)) {
item = keys.splice(i, 1)[0];
result.push(item);
used.add(item);
continue;
}
i++;
}
} while (keys.length && keys.length !== length)
console.log('circle', ...keys);
result.push(...keys);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
要首先获取不依赖项的项目,可以过滤键并直接获取值.
For getting the items first who have no dependency, you could filter the keys and take the values directly.
var dependencies = { A: [], B: ['A'], C: ['A', 'B'], D: ['F'], E: ['D', 'C'], F: [], G: ['H'], H: ['G'] },
keys = Object.keys(dependencies),
used = new Set,
result = [],
items, length;
do {
length = keys.length;
items = [];
keys = keys.filter(k => {
if (!dependencies[k].every(Set.prototype.has, used)) return true;
items.push(k);
});
result.push(...items);
items.forEach(Set.prototype.add, used);
} while (keys.length && keys.length !== length)
console.log('circle', ...keys);
result.push(...keys);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
这篇关于JavaScript-根据依赖关系树排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!