Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

18
  • 13
    Computing the Array difference is a so called set operation, because property lookup is the very own job of Sets, which are orders of magnitude faster then indexOf/includes. Simply put, your solution is very inefficient and rather slow. Commented Oct 18, 2016 at 19:35
  • 3
    @ftor but with Set, values have to be unique, no? Commented Oct 23, 2016 at 14:20
  • 3
    @LuisSieira I get that it would work for [1,2,3] [2,3,5] given that the numbers are unique but if you had say [1,1,2,3] [1,2,3,5] and expected [1] you couldn't use Set. Your solution wouldn't work either though :-/ I ended up creating this function because I couldn't figure out a satisfactory way to do it more succinctly. If you have any ideas on how to do that, I'd love to know! Commented Oct 24, 2016 at 10:31
  • 9
    Isn't Array.includes() ES7 feature instead of ES6? (1) (2) — and to continue, with ES6 you could use Array.some() e.g. let intersection = aArray.filter(a => bArray.some(b => a === b)), no? Commented May 24, 2018 at 8:18
  • 2
    See also Nina Scholz's answer. I tried using a binary search instead of includes, which obviously gave massive speed increases (improved the complexity from O(n^2) to O(n log2 n)). Using her little function instead of binary search came out 2-3x times faster, especially when the arrays were almost the same. 10x+ when using crazy arrays (100,000,000 elements)... Commented Aug 23, 2022 at 15:02