Как найти похожие объявления по названию и описанию?
Мне нужно написать функцию которая будет сравнивать одно объявление с массивом других объявлений и будет создавать массив с похожими объявлениями. Два объявления считаются похожими, если они содержат хотя бы одно и то же слово в заголовке и описании. Массив выглядит так:
[
{title: "Test", description: "hello", id: 22},
{title: "Test two", description: "hi", id: 49},
{title: "Test three", description: "hello there", id: 100},
{title: "Test four", description: "oh", id: 129},
]
Спасибо!
Ответы (1 шт):
Автор решения: Qwertiy
→ Ссылка
function getWords(msg) {
var res = new Set()
for (var key of ['title', 'description']) {
for (var word of msg[key].match(/\w+/) || []) {
res.add(word)
}
}
return res
}
function indexMsgs(msgs) {
var dict = new Map()
for (var msg of all) {
for (var word of getWords(msg)) {
var cur = dict.get(word)
if (!cur) dict.set(word, cur = [])
cur.push(msg)
}
}
return dict
}
var all = [
{title: "Test", description: "hello", id: 22},
{title: "Test two", description: "hi", id: 49},
{title: "Test three", description: "hello there", id: 100},
{title: "Test four", description: "oh", id: 129},
]
var dict = indexMsgs(all)
function getSimilar(msg) {
return [...new Set([...getWords(msg)].flatMap(x => dict.get(x) || []))]
}
console.log(getSimilar(all[0]))
console.log(getSimilar({ title: "oh", description: "" }))
.as-console-wrapper.as-console-wrapper { max-height: 100vh }