2

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.

2 Answers 2

10

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.
Sign up to request clarification or add additional context in comments.

Comments

2

Try Array#flatten

Returns a new array that is a one-dimensional flattening of self (recursively).

=> [[2700, 177, 2092, 176, 188], [123, 1234], []].flatten
#> [2700, 177, 2092, 176, 188, 123, 1234]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.