0

How can I do this in JavaScript? It should print 'Found' when it hits words in big_list

big_list = ['this', 'is', 'a', 'long', 'list', 'of' 'words']

needle = ['words', 'to', 'find']

for i in big_list:
    if i in needle:
        print('Found')
    else:
        print('Not Found')

I know the general if/else structure but am unsure the syntax:

if (big_list in needle) {
  console.log('print some stuff')
} else {
  console.log('print some other stuff')
}

2 Answers 2

2

You can use includes function with a for loop like this:

for (let i = 0; i < big_list.length; i++)
{
    if (needle.includes(big_list[i])) console.log("Found");
    else console.log("Not found");
}

Or using forEach:

big_list.forEach(function(e) { 
     if (needle.includes(e)) console.log("Found");
     else console.log("Not found");
});
Sign up to request clarification or add additional context in comments.

Comments

1

You've almost got it already, but there are a few things of note. First, the in keyword works differently in javascript than it does in python. In python, it can be used to check if an item is a member of a collection, but in javascript, it checks if the item is a key of an object. So:

"foo" in {foo: "bar"} // True

but

"foo" in ["foo", "bar"] // False

Because in the second case, while "foo" is a member of the array, the in keyword is looking for it as a key. On those lines:

"0" in ["foo", "bar"] // True

Since "0" is a key of the array (namely the key pointing to the first item)

Other than that, your code can be adapted to javascript without changing much. Just declare your variables using var, const, or let, use braces with your if's and replace the calls with their javascript equivalents:

/*

# Python Code:
big_list = ['this', 'is', 'a', 'long', 'list', 'of', 'words']

needle = ['words', 'to', 'find']

for i in big_list:
    if i in needle:
        print('Found')
    else:
        print('Not Found')

*/

// Now in javascript:

const big_list = ['this', 'is', 'a', 'long', 'list', 'of', 'words']
const needle = ['words', 'to', 'find']

for (let i of big_list) {
  if (needle.includes(i)) {
    console.log('Found')
  } else {
    console.log('Not Found')
  }
}

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.