I have two arrays:
array1 = ["hello","two","three"]
array2 = ["hello"]
I want to check if array2 contains 1 or more array1 words.
How can I do that using Coffeescript?
Use the inbuilt ES6 function some() to iterate through each and every element of first array and to test the array. Use the inbuilt function includes() with second array to check if element exist in the first array or not. If element exist then return true else return false.
You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.
Use forEach() to find an element in an array The Array.
Found a way to check for the intersection between two arrays using this CoffeeScript chapter. CoffeeScript seems pretty awesome looking at this.
If the array resulting after the intersection of the elements contains at least one item, then both arrays have common element(s).
intersection = (a, b) ->
[a, b] = [b, a] if a.length > b.length
value for value in a when value in b
x = ["hello", "two", "three"]
y = ["hello"]
intersection x, y // ["hello"]
Try it here.
Thought I would throw my own coffeescript one-liner madness :-P
true in (val in array1 for val in array2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With