Hello guys I need help to figure out an expression. I got phrases like
JavaScript
x
8
1
const phrases = [
2
"This is dummy sentences of example 05",
3
"It needs help of your example 2022",
4
"This dummy datas will be used for any example of matched needs "
5
]
6
var target = "example dummy datas 01"
7
8
expectedOutput = "This dummy datas will be used for any example of matched needs "
As you see above, target’s three words matches with last sentence. The purpose is to find sentence includes most matched words.
I did like
JavaScript
1
16
16
1
const phrases = [
2
"This is dummy sentences of example 05",
3
"It needs help of your example 2022",
4
"This dummy datas will be used for any example of matched needs "
5
]
6
var target = "example dummy datas 01"
7
8
target = target.split(' ')
9
10
const expectedOutput = phrases.filter(sentence => {
11
12
return target.every(word => {
13
return sentence.indexOf(word) !== -1
14
})
15
})
16
console.log(expectedOutput)
But it gives nothing
Advertisement
Answer
Use .filter()
, .some()
, .includes()
and .sort()
methods as explained below.
JavaScript
1
20
20
1
const phrases = [
2
"This is dummy sentences of example 05",
3
"It needs help of your example 2022",
4
"This dummy datas will be used for any example of matched needs "
5
]
6
var target = "example dummy datas 01"
7
8
target = target.split(' ');
9
10
const expectedOutput = phrases
11
//Find if any phrases contain at least one target word
12
.filter( phrase => target.some(word => phrase.includes(word)) )
13
//Now sort the phrases in descending order of how many words matched
14
.sort( (a,b) => target.filter(word => b.includes(word)).length - target.filter(word => a.includes(word)).length )
15
//The first phrase matched the most words or at least the first and second matched the most words, otherwise return ''
16
[0] || '';
17
18
19
console.log( expectedOutput );
20
//Output: "This dummy datas will be used for any example of matched needs "