Javascript ES5's forEach() method and I had been getting along quite well until last week when I was trying to implement it inside this one simple ...
For further actions, you may consider blocking this person and/or reporting abuse
Hi! You might be looking for a function named
Array.some
. It checks that at least one item in an array verifies a given predicate, and is early-terminating.Here's the code using a hash table (so both arrays must contain only strings) as you did:
:)
Yes that sure does the job <3! Thanks for recommending!
And you may want to use
new Set(array1)
instead of yourhashTable
.(disclaimer: untested code snippet)
Awesome! Here's my tested code:
Very clean and time optimized! Thanks again everyone!
I prefer
for.. of
loop since it's more intuitive and has shorter syntax than the usualfor
loop.BTW,
Array#forEach
is ES5 not ES6 feature ;)Definitely! Thanks for mentioning <3
You might want to consider using Array.prototype.some. This will run a function against each element in an array, until something returns truthy. Then, it immediately stops and returns true. This will help a lot if you have a large number of items in the second array.
developer.mozilla.org/en-US/docs/W...
Oh yeah totally forgot about that little guy. Thanks for mentioning! Will definitely use it next time similar needs come up!
Hi, sorry I know it's just a code comment but in the first step when you iterate through the first array and tag items to true, your last output is dog. Should it not be kangaroo? ๐ค
Thanks for this article๐
Hey my bad - I totally forgot about the guy! (poor little kangaroo!). Already put it back in with the gang! Thanksss for pointing this out! <3
I was thinking why foreach ALWAYS returns undefined by design. But in your use case it would have been better to use find & return whatever it returns. It can be chained and will break once the element is found.
Hi! Hace you considered using the .includes() method? If not, can you tell me why? I'm kind of new to JS.
Thanks for your article!
Hi Mike yes you totally can use
includes()
however it would make the function not algorithm-wise because you gotta nest one loop inside another:So you nest
includes()
which loops thru array2 insideforEach()
, which is not ideal in terms of time complexity if you have a huge amount of items in your arrays.