Hola chicos necesito ayuda para descifrar una expresión. tengo frases como
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 "Como puede ver arriba, las tres palabras del objetivo coinciden con la última oración. El propósito es encontrar oraciones que incluyan la mayoría de las palabras coincidentes.
Me gustó
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)pero no da nada
Utilice .filter() , .some( .some() , .includes() y .sort() como se explica a continuación.
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 "Debe filtrar los elementos de la cadena de target que son numéricos:
target = target.split(' ').filter(w => isNaN(w))Esto funciona de la siguiente manera:
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)