donald
donald

Reputation: 23747

Coffeescript: Array element matches another array

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?

Upvotes: 9

Views: 4751

Answers (6)

m.e.conroy
m.e.conroy

Reputation: 3538

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

Upvotes: 1

Craig
Craig

Reputation: 540

Thought I would throw my own coffeescript one-liner madness :-P

true in (val in array1 for val in array2)

Upvotes: 7

Ricardo Tomasi
Ricardo Tomasi

Reputation: 35253

contains = (item for item in array2 when item in array1)

(reverse the arrays to show double entries in array1)

Upvotes: 2

Eric Bock
Eric Bock

Reputation: 1782

You could try:

(true for value in array1 when value in array2).length > 0

Upvotes: 2

Anurag
Anurag

Reputation: 141889

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.

Upvotes: 12

alessioalex
alessioalex

Reputation: 63683

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

Upvotes: 1

Related Questions