how can we filter a list and show result if any part of the input text match list javascript
I have data that would come from api that I am trying to filter. Basically what I want to do is have input text and if any word of my input text is found in the source I want to get the value
//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) // reading
You can use includes
here as:
1)
const findText = 'is there a jerry';
const list = ['jerry', 'reading', 'good'];
const results = list.filter((e) => findText.includes(e));
console.log(results); // jerry
2)
// 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);
You can also use Set here as:
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 introduced 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']
includes doesn’t have Internet Explorer support, though. In ECMAScript 5 or older environments, use String.prototype.indexOf, which returns -1 when a substring cannot be found:
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']