#Library function for two lists intersecting?

34 messages · Page 1 of 1 (latest)

restive rapids
#

Is there a library function for taking two string arrays and detecting whether or not they intersect?

Ie:

// Given the following arrays
const a = [1,2,3,4];
const b = [3,4,5,6];
const c = [6,7,8,9];
// a intersects b, b intersects c, a does not intersect c

If not, I can write my own... but if it is standard, would prefer to use that 🙂

#

Note - I'm just looking for a boolean, not an array of the shared elements

tough crest
#

probably in lodash/equivalents

tough crest
restive rapids
#

yeah... I have something like this now:

#
(goal) => goal.programs.filter((x) => programIds.includes(x)).length > 0
#

where the lists are goal.programs and programIds

tough crest
#

well yeah that's how you'd do it usually

violet fern
tough crest
#

some, not any

violet fern
restive rapids
#

Just generalized

export const arrayIntersects = (a: string[], b: string[]): boolean => {
  return a.filter(b.includes).length > 0;
}
#

ah some is better

#

thanks

violet fern
restive rapids
#

Ok - thanks!

#

!resolved

tough crest
#

got derailed;
some here is O(1) space and O(n*m) time, compared to
filter is O(n) space and O(n*m) time
Set would be O(n+m) space and O(n+m) time i think?

restive rapids
#

By set do you mean by translating the array into a set?

tough crest
#

yeah

#

it wasn't mentioned i just thought of it a bit lol

#

it's kinda horrendous

#

Set([...a, ...b]).size !== a.length + b.length

restive rapids
#

that could be useful if I have large arrays with repeated values

tough crest
#

i think in weird ways sometimes

restive rapids
#

but in my case I don't

tough crest
#

it also assumes the arrays are already sets themselves

restive rapids
#

It could reduce the size of n and m before doing the operation

#

but if you have mostly unique values you're just adding overhead to convert to/from the set and then use counterintuitive code

tough crest
#

right but now your algorithm is O(n+m) in space instead of O(1)

restive rapids
#

but it's worth considering, and I did use set theoretic language in my questin 🙂

#

fair

violet fern
#

using it on two Sets, or an Array and a Set, instead of two Arrays would make it O(n*log(m)) for time I think
cause Sets do use a form of binary search for lookup, yeah?

(however this does not include the cost of converting an array to a set)