Я написал это, чтобы создать Trie из списка слов.Возможно, вы могли бы адаптировать его для ваших целей:
const sortLetters = (string) => {
// I'm using a space as a key here because it is the only letter that cannot by any definition be construed as a letter constituting a word.
let obj = {' ': "\n"};
for (let i = string.length - 1 ; i >= 0 ; i--) {
const tmp = {};
tmp[string[i]] = obj;
obj = tmp;
}
return obj;
}
const wordMap = {};
console.time("Build trie");
allWords.forEach(function(value){_.merge(wordMap, sortLetters(value))});
console.timeEnd("Build trie");
console.log(wordMap);