How to concatenate contents of two string arrays with same number of elements


(markus mayer) #1

Hi,
I have to string arrays with the same number of elements. Is it possible to create a new string array (or overwrite one of the existing ones) containing the string concatentation of the elements from both arrays at the same index.

Say:

Array A:
  ->foo
  ->forest

Array B:
  ->bar
  ->gump

Result:
   ->foobar
   ->forestgump

Any help appreciated!
Bye,
Markus


(Magnus Bäck) #2

I don't believe there's any stock filter that does this, but a Ruby filter can do the job:

ruby {
  code => "
    event['zipped'] = event['array1'].zip(event['array2']).map! { |item|
      item[0] + item[1]
    }
  "
}

zip() joins the two arrays to an array where each element is a two-element array of the corresponding items, in your example [["foo", "bar"], ["forest", "gump"]], and the map operation flattens the array via concatenation.

(Someone with better Ruby-fu can probably suggest a more elegant solution.)


(markus mayer) #3

Thanks. I suspected that and was just starting a ruby tutorial when your post came in (one new language per year:-))
Just if any one stumbles accross Magnus' solution. You have to take care that the input arrays are not null (or nil that is in ruby). Otherwise you get NoSuchMethod errors...

So do something like:

if(!event['array1'].nil?)
   event['zipped'] = event['array1'].zip(event['array2']).map! { |item|
       item[0] +'; '+ item[1]
   }
end

(Magnus Bäck) #4

Indeed—and one should also check that the arrays have the same number of elements and that the fields exist in the first place.


(system) #5