Tengo datos que vendrían de API que estoy tratando de filtrar. Básicamente, lo que quiero hacer es tener texto de entrada y si alguna palabra de mi texto de entrada se encuentra en la fuente, quiero obtener el valor
//example 1 the word jerry is found in the list so it will console.log jerry findText ='is there a jerry' const list = ['jerry', 'reading', 'good'] const results = list.filter(e => e === findText) console.log(results) // jerry //example 2. the word reading and everyone is found in the list so console.log reading and good. findText ='is reading for everyone' const list = ['jerry', 'reading', 'good', everyone] const results = list.filter(e => e === findText) console.log(results) // readingPuede usar includes aquí como:
1)
const findText = 'is there a jerry'; const list = ['jerry', 'reading', 'good']; const results = list.filter((e) => findText.includes(e)); console.log(results); // jerry2)
// example 2. the word reading and everyone is found in the list so console.log reading and good. const findText = 'is reading for everyone'; const list = ['jerry', 'reading', 'good', 'everyone']; const results = list.filter((e) => findText.includes(e)); console.log(results);También puede usar Establecer aquí como:
const findText = 'is reading for everyone'; const list = ['jerry', 'reading', 'good', 'everyone']; const findTextSet = new Set(findText.split(' ')); const results = list.filter((word) => findTextSet.has(word)); console.log(results); // ['reading', 'everyone']ECMAScript 6 introdujo String.prototype.includes :
let findText ='is reading for everyone'; const list = ['jerry', 'reading', 'good', 'everyone']; const results = list.filter(e => findText.includes(e) ); console.log(results); // ['reading', 'everyone']Sin embargo, incluye no es compatible con Internet Explorer. En entornos ECMAScript 5 o anteriores, utilice String.prototype.indexOf , que devuelve -1 cuando no se puede encontrar una subcadena:
let findText ='is reading for everyone'; const list = ['jerry', 'reading', 'good', 'everyone']; const results = list.filter(e => findText.indexOf(e) !== -1 ); console.log(results); // ['reading', 'everyone']