Home > database >  Javascript find matched sentence with predefined words
Javascript find matched sentence with predefined words

Time:02-11

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

CodePudding user response:

You need to filter out the elements from the target string which are numeric:

target = target.split(' ').filter(w => isNaN(w))

This works as 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(' ').filter(w => isNaN(w))

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

CodePudding user response:

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
[0];


console.log( expectedOutput );
//Output: "This dummy datas will be used for any example of matched needs "

  • Related