Convert array with 2 equal values to single value

Greetings

My events sometimes have a field "foo" equal to a single value, sometimes an array of multiple distinct values, and sometimes an array of exactly two equal values.
I would like to convert the last case to the first case.
For example, I would like to convert this

"foo": [
  "bar",
  "bar"
],

to

"foo": "bar"

Is there an easy method to do this? I was thinking i could do something along those lines:

if foo[0] == foo[1]
  mutate {
    foo_tmp = foo[0]
    remove foo
    foo = foo_tmp
    remove foo_tmp
  }

but I am unsure about the exact syntax when it comes to array element access.

Edit after @Badger's comment

Hi, what do you think of:

ruby {
  code => '
     foo = event.get("foo")
     foo = foo.kind_of?(Array) && foo.uniq.length == 1 ? foo.uniq[0] : foo
     event.set("foo", foo)
  '
}
1 Like

That will convert [ "bar", "bar" ] to

       "foo" => [
    [0] "bar"
],

not

"foo" => "bar"

It also results in a ruby exception when [foo] is not an array, so you need some more code around it.

1 Like

Perfect, does exactly what I needed.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.