简体   繁体   中英

How to find most perfect matching of some part of a string with an object's string value from a list of objects in javascript?

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.

  1. As we can see there are two true results for "Higher Education" and "Higher Education in Biology". But I only want the last one as it is more accurate than the first one. How to do that?
  2. My storedList might have upto 60,000 objects in the list. So for checking the string str1 I need to loop for 60,000 times with my process. And what if I have to check the storedList for 1000 different strings, It's 60,000 * 1000 times!

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM