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?
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.
intersection = (a, b) ->?a, b = b, a if (a.length > b.length). The construct of putting the if conditional at the end of a statement in Ruby is something I've started to love. In JavaScript, these are known as destructuring assignments.I've made a function is_in, look at my example:
array1 = ["hello","two","three"]
array2 = ["hello"]
is_in = (array1, array2) ->
for i in array2
for j in array1
if i is j then return true
console.log is_in(array1, array2)
After having a look at the intersection example, I can achieve this in another way:
intersection = (a, b) ->
[a, b] = [b, a] if a.length > b.length
return true for value in a when value in b
array1 = ["hello","two","three"]
array2 = ["hello"]
console.log intersection(array1, array2)