You can solve it using a trie
Whenever you get a string, just traverse your tree and eventually add any leaf (if you can't traverse more)
const input = ['apples', 'bananas.kivi.grape', 'bananas.orange', 'bananas.strawberry', 'apples.are.good', 'apples.are.not.good'];
const Trie = () => {
const root = {}
const add = s => {
s.split('.').reduce((acc, tok) => {
if (!acc[tok]) {
// add the leaf
acc[tok] = { children: {} }
}
// traverse the node
return acc[tok].children
}, root)
}
const toJSON = (node = root) => {
return Object.entries(node).map(([name, { children }]) => ({
name, children: toJSON(children)
}))
}
return { add, toJSON }
}
const t = Trie()
input.forEach(t.add)
console.log(JSON.stringify(t.toJSON(), null, 2))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…