11

Possible Duplicate:
Simplest code for array intersection in javascript

Let's say I have arrays:

[0,1]

and

[1,2,3]

I need to verify whether these arrays have common elements, for this case it would be 1

Using jQuery i check it following way:
1. get length of 1st array
2. get length of 2nd array
3. merge arrays
4. get length of merged array
5. if lenght of merged array not equal lenghts 2 initial arrays,that they have common elements

One line code is:

(event2Zone[0].length+event2Zone[1].length)==$.unique($.merge(event2Zone[0].zo,event2Zone[1].zo)).length

Is there more standard or gracefull way to do the same operation?

Community
  • 1
  • 1
sergionni
  • 13,290
  • 42
  • 132
  • 189
  • 2
    http://stackoverflow.com/q/1885557/365188 – Ozair Kafray Jul 20 '12 at 14:28
  • You wanted to use != instead of ==? – Bergi Jul 20 '12 at 14:29
  • i think it does't matter what flag is returned – sergionni Jul 20 '12 at 14:31
  • 4
    One liner: ECMA5: `a.some(function(v) { return b.indexOf(v) !== -1; })` – Andreas Louv Jul 20 '12 at 14:33
  • @sergionni https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some - Returns `true` if any truly values is returned from the loops. Else returns `false`. – Andreas Louv Jul 20 '12 at 14:39
  • 1
    This isn't a duplicate. This question is asking how to **test if** any intersection exists between two arrays. The linked question asks **to find the intersecting values**. There might be an answer that solves this question, but doesn't return the values (like the examples given in the question based on `length`). Voting to reopen. – user56reinstatemonica8 May 10 '15 at 10:42
  • (also re. the jQuery examples given, note that ["jQuery.unique() only works on arrays of DOM elements, **not strings or numbers**"](http://api.jquery.com/jquery.unique/) ) - it does sometimes work, but [can't be relied on](http://stackoverflow.com/questions/10191941/jquery-unique-on-an-array-of-strings) – user56reinstatemonica8 May 10 '15 at 11:09
  • 1
    `const hasIntersection = (a, b) => a.some(v => b.includes(v));` ES6 using @andlrc I think marking this as duplicate is wrong since the other question is about `getIntersetction` and not `hasIntersection` which are 2 differnet solutions – select Apr 04 '17 at 21:29

0 Answers0