I have a list in frontend storedList . I need to check if some part of string str1 perfectly matches with any value of text parameter in storedList . I have tried using includes() and got output given below.
let storedList = [
{ id: 1, text: 'Higher Education' },
{ id: 2, text: 'Higher Education in Physics' },
{ id: 3, text: 'Higher Education in Chemistry' },
{ id: 4, text: 'Higher Education in Math' },
{ id: 5, text: 'Higher Education in Biology' },
{ id: 6, text: 'Higher Education in History' },
{ id: 7, text: 'Higher Education in Economics' },
];
let str1 = 'unnecessay texts Higher Education in Biology unnecessary texts';
for (let row of storedList) {
console.log(str1.includes(row.text));
// output
// true
// false
// false
// false
// true
// false
// false
}
Now I have two problems.
Really need a better and efficient solution.
You can use Array.reduce()
and take the object with the longer text, which is also included in str1
:
const storedList = [ { id: 1, text: 'Higher Education' }, { id: 2, text: 'Higher Education in Physics' }, { id: 3, text: 'Higher Education in Chemistry' }, { id: 4, text: 'Higher Education in Math' }, { id: 5, text: 'Higher Education in Biology' }, { id: 6, text: 'Higher Education in History' }, { id: 7, text: 'Higher Education in Economics' }, ]; const str1 = 'unnecessay texts Higher Education in Biology unnecessary texts'; const result = storedList.reduce((r, o) => o.text.length > r.text.length && str1.includes(o.text)? o: r ); console.log(result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.