Search code examples
javascriptnode.jsangularmongodb-atlaskeyword-search

How to find keywords in arrays of scripts using Javascript hopefully client-side


I'm facing this problem and I don't know the right approach to solve it. I have an array of keywords, for example:

keywordArray = ["Javascript", "Python", "R", "Data Science", "Front-end", "Amazon Web Services", "Amazon DynamoDB"]

Now I need to find just once occurrence in an array of string and return that occurrence. For example:

stringArray = ["I love learning JavaScript but I would also like to learn Data Science using R", "I don't buy at Amazon", "RnB Music"]

In this example I need to return an array containing Javascript, Data Science and R. If I remove the first string from stringArray, then it should not return R (I'm thinking it may be found in "RnB Music").

I would like to do this on the client side but I tried indexOf(), contains(), etc., but it isn't working properly.

So, can I do it on the client-side? if the answer is Yes, then how can I do this? If not, then is it possible to do it on NodeJS? Should I use a cloud service for this?

I'm currently using Angular, Express, NodeJS and MongoDB Atlas, which it has a Fulltext search service and works quite good. I may try to do it there but I don't know if its cost efficient.


Solution

  • Okay so, you have the first array :

    const keywordArray = ["JavaScript", "Python", " R", "Data Science", "Front-end", "Amazon Web Services", "Amazon DynamoDB"]; 
    

    and the second one is the list of strings

    const stringArray = ["I love learning JavaScript but I would also like to learn Data Science using R", "I don't buy at Amazon", "RnB Music"];
    

    So you need to iterate over both arrays and check with includes() method.

    Like this :

    const keywordArray = ["JavaScript", "Python", " R", "Data Science", "Front-end", "Amazon Web Services", "Amazon DynamoDB"];
        
        const stringArray = ["I love learning JavaScript but I would also like to learn Data Science using R", "I don't buy at Amazon", "RnB Music"];
        
        const result_array = [];
        
        for (let i = 0; i < stringArray.length; i++)
        {
          for (let d = 0; d < keywordArray.length; d++)
          {
              if (stringArray[i].includes(keywordArray[d]))
              {
                result_array.push(keywordArray[d]);
              }
                  
          }
        }
        
        console.log(result_array);