1

I have array that contain strings

commentArray ={ "words":[ "xyz", "abc", "random", "sample" ] }

And I want to match string

 var comment = "hello world ran"

What I'm doing is

commentArray.words.find(words => {
    if (comment.toLowerCase().includes(words.toLowerCase())) {
      return true;
    }
  });

it giving true because "random" contains "ran" but I want true only if matches whole string not characters.

1
  • 3
    Use === instead of .includes? Commented Mar 5, 2019 at 8:42

5 Answers 5

3

You can do this:

const commentArray = {
    "words": [ "xyz", "abc", "random", "sample" ] 
};

const comment = "hello world ran";
const commentArr = comment.split(' ');

commentArray.words.find(words => {
    if (commentArr.includes(words.toLowerCase())) {
        return true;
    }
});
Sign up to request clarification or add additional context in comments.

Comments

2

var commentArray ={ "words":[ "xyz", "abc", "random", "sample" ] }

 var comment = "hello world random";
 var commentInWords = comment.split(" ");
 var res = commentArray.words.filter(words => {
    let a = _.includes(commentInWords,words.toLowerCase())
        if (a) {
          return true;
        }else{
          return false;
      }
 });

 console.log(res)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

2 Comments

I'm getting _ is not defined
@chetankumar, "_.includes" is a lodash function. you need to import cdn for that. you can get it from this link cdnjs.com/libraries/lodash.js
1
var commentArray ={ "words":[ "xyz", "abc", "random", "sample" ] };
var comment = "hello xyz";
var commentInWords = comment.split(" ");
 var res = commentArray.words.filter(words => {
   for(var i = 0; i <= commentInWords.length; i++){
    var a = (commentInWords[i] == words.toLowerCase());
        if (a) {
          return true;
        }
   }
 });

 console.log(res)

Comments

0

1) Split the string "comment" into array of words

2) For each word from comment, try to find it in you "words" array. You can use something like your comparison but you need to compare with === instead of includes, of course.

1 Comment

@chetankumar Did you try this too, as stated by Pac0? : You can use something like your comparison but you need to compare with === instead of includes, of course. This just must work, because strict equal will never return true with "ran" against "random" and vice-versa.
0

commentArray.words.some( word => ~comment.split(" ").indexOf(word))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.