Skip to content
Advertisement

Javascript find matched sentence with predefined words

Hello guys I need help to figure out an expression. I got phrases like

const phrases = [
  "This is dummy sentences of example 05",
  "It needs help of your example 2022",
  "This dummy datas will be used for any example of matched needs "
]
var target = "example dummy datas 01"

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

const phrases = [
  "This is dummy sentences of example 05",
  "It needs help of your example 2022",
  "This dummy datas will be used for any example of matched needs "
]
var target = "example dummy datas 01"

target = target.split(' ')

const expectedOutput = phrases.filter(sentence => {

  return target.every(word => {
    return sentence.indexOf(word) !== -1
  })
})
console.log(expectedOutput)

But it gives nothing

Advertisement

Answer

Use .filter(), .some(), .includes() and .sort() methods as explained below.

const phrases = [
  "This is dummy sentences of example 05",
  "It needs help of your example 2022",
  "This dummy datas will be used for any example of matched needs "
]
var target = "example dummy datas 01"

target = target.split(' ');

const expectedOutput = phrases
//Find if any phrases contain at least one target word
.filter( phrase => target.some(word => phrase.includes(word)) )
//Now sort the phrases in descending order of how many words matched
.sort( (a,b) => target.filter(word => b.includes(word)).length - target.filter(word => a.includes(word)).length )
//The first phrase matched the most words or at least the first and second matched the most words, otherwise return ''
[0] || '';


console.log( expectedOutput );
//Output: "This dummy datas will be used for any example of matched needs "
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement