Home > Software engineering >  How to remove array elements where element's fields are NULL
How to remove array elements where element's fields are NULL

Time:10-26

array = [[1555,100],[nil,95],[1774,nil],[1889,255]]

What would be the best way to remove the 2nd and 3rd elements from array since they have NULL fields?

Expected output :

array = [[1555,100],[1889,255]]

CodePudding user response:

arr = [[1555,100],[nil,95],[1774,nil],[1889,255]]
arr.reject { |a,b| (a && b).nil? }
  #=> [[1555, 100], [1889, 255]]

CodePudding user response:

And yet another option:

array.reject { |a| a.any?(&:nil?) }

It is very similar to Cary Swoveland's answer, but will work with arrays of any length

CodePudding user response:

Use .compact to remove nil elements from array of arrays

array.map(&:compact)

# array = [[1555,100], [95], [1774], [1889, 255]]

Edit

Use .reject! to remove sub arrays containing nil elements.

array.reject! { |e| e.any? nil }

# array = [[1555,100], [1889,255]]

CodePudding user response:

Ruby 2.7

There is now!

Ruby 2.7 is introducing filter_map for this exact purpose. It's idiomatic and performant, and I'd expect it to become the norm very soon.

array.filter_map{|i| i unless i.include?(nil)}
#=> [[1555, 100], [1889, 255]] 
  • Related