Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby new unique array of nested array items

Looking for a way to reduce a nested list of arrays, into a single array of items that are unique, and drop any empty arrays.

Looking to reduce this array:

[[2700, 177, 2092, 176, 188], [123, 1234], []]

Down to this new array:

[2700, 177, 2092, 176, 188, 123, 1234]

Have tried array.uniq.compact, but did not work.

Thanks for any suggestions.

like image 897
tmartin314 Avatar asked Mar 24 '26 19:03

tmartin314


1 Answers

You need to flatten the array first.

array.flatten.uniq

A few notes:

  • Array#flatten merges all child arrays into the top level array. Since empty arrays do not contain any elements, they will automatically be removed.
  • Array#compact returns a new array with the nil elements removed.
  • Array#uniq returns a new array with only unique elements.
like image 163
fbonetti Avatar answered Mar 27 '26 07:03

fbonetti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!