0

I have problem with comparing many arrays in one array. I need to get element which exists in every array. It's look like this one:

array= [[11,12,13,14],[55,66,13],[13,15,17,22,34],[4,6,8,13]]

I need to get only: 13 - because its on every array, how to get it ?

Nilay Singh
  • 2,201
  • 6
  • 31
  • 61
AdamM
  • 163
  • 1
  • 1
  • 9

2 Answers2

5

This should work

a.inject(:&)
Nithin
  • 3,679
  • 3
  • 30
  • 55
-1

You could use inject as mentioned by Nithin in another answer.

Another option is to use reduce:

ary = _
 => [
      [11, 12, 13, 14],
      [55, 66, 13],
      [13, 15, 17, 22, 34],
      [4, 6, 8, 13]
    ]

ary.reduce(:&)
 => [13]

# which is a short-hand for:
ary.reduce { |out, elem| out & elem }
 => [13]
Jagdeep Singh
  • 4,880
  • 2
  • 17
  • 22