Coffeescript:Array元素与另一个数组匹配

时间:2011-12-21 05:22:07

标签: javascript node.js coffeescript

我有两个数组:

array1 = ["hello","two","three"]
array2 = ["hello"]

我想检查array2是否包含1个或更多array1字。

我怎么能用Coffeescript做到这一点?

6 个答案:

答案 0 :(得分:12)

使用此CoffeeScript chapter找到了检查两个数组之间交集的方法。 CoffeeScript看起来非常棒。

如果在元素交集之后得到的数组包含至少一个项,则两个数组都有共同的元素。

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"]

试试here

答案 1 :(得分:7)

以为我会抛出自己的咖啡因单线疯狂:-P

true in (val in array1 for val in array2)

答案 2 :(得分:2)

你可以尝试:

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

答案 3 :(得分:2)

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

(反转数组以显示array1中的双重条目)

答案 4 :(得分:1)

我已经创建了一个函数is_in,看看我的例子:

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

看了一下交叉点的例子,我可以用另一种方式实现这个目的:

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

答案 5 :(得分:1)

以防有人来到这里并且正在寻找与交叉点相对的差异

difference = (val for val in array1 when val not in array2)

这将为您提供 array1 中所有值的数组(差异),而不是 array2

相关问题