Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 524
donald Avatar asked Dec 21 '11 05:12

donald


People also ask

How do you check if an element in an array is in another array?

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.

How do you check if an element of an array is in another array JavaScript?

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.

How do you find an array within an array?

Use forEach() to find an element in an array The Array.


2 Answers

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.

like image 141
Anurag Avatar answered Sep 28 '22 07:09

Anurag


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

true in (val in array1 for val in array2)
like image 42
Craig Avatar answered Sep 28 '22 08:09

Craig