efultz efultz - 1 year ago 82
CoffeeScript Question

coffee script - remove from one array based on second array contents

I have 2 arrays - one has attribute called vcdName and the other has attribute called name. I want to remove from array 1 all entries where I find the value of vcdName in the second array. So:
array one
data...vcdName=a
data...vcdName=b

array two
data...name=a

I want to filter array one and remove the first entry (because vcdName value a is found in array two).

I understand I can use lodash functions and I tried the following. I believeusing is will return me those entries that match and I need to put in filteredArray those entries where no match is found in arraytwo.

filteredArray = _.filter(@arrayone, (vcd) -> vcd.vcdName is @arraytwo)


I hope I have not gotten too confusing. It feels this should be moderately easier than I am making it.

Generically I need to do this

for each entry in arrayone
for each entry in arraytwo
does entry from arrayone.vcdName == arraytwo.name - if yes then I do not want that entry from arrayone


I hope that helps

Answer Source

filter is in js core so I don't see why you'd need to use the lodash function, but anyway you can do it like this:

arraytwo_names = @arraytwo.reduce (dict, entry) ->
  dict[entry.name] = true
  dict
, {}

results = @arrayone.filter (x) ->
  !arraytwo_names[x.vcdName]

The reduce is not strictly speaking necessary, since you could loop through arraytwo each iteration of the filter, but it is an optimization and makes the runtime O(N) and not O(N^2).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download