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?
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.
Thought I would throw my own coffeescript one-liner madness :-P
true in (val in array1 for val in array2)
You could try:
(true for value in array1 when value in array2).length > 0
contains = (item for item in array2 when item in array1)
(reverse the arrays to show double entries in array1
)
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)
Test here
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)
Test here
Just in case someone comes here and is looking for the difference as opposed to the intersection
difference = (val for val in array1 when val not in array2)
This will give you an array (difference) of all values in array1 but not in array2