Flattening an Array is a common Leetcode and interview question. And for the most part I never thought I would meet it at my day job (as with most questions you meet during the interview). However, I am doing an interating search through a DB in rails and I am using the pluck method.
The pluck method will return an array of the items you want to pluck, for instance
User.find_by(category: "director").pluck(:email, :user_name)
=> [["johndoe@example.com", "John Doe"], ["janedoe@example.com", "Jane Doe"]]
But since I am doing an iterative search, (not the most efficient, but I am yet to optimize), I store the results of each fetch in an array variable which means I end up with a deeply nested array. (Again, not the most efficient, I know.)
Enter the flatten
command. Flatten will return a new array that is a one-dimensional flattening of self
But I didn't want a one dimensional array. I want to preserve the results of the pluck command. So if you go through the docs, you find that flatten actually takes in an integer that determines the level of recursion to flatten.
This then means that we can do this
[[[1,2],[3,4]]].flatten(1)
=> [[1,2],[3,4]]
[[[1,2],[3,4]]].flatten(2)
=> [1,2,3,4]
This was pretty useful, because if you have a multidimensional array where each element is an array of 2 elements, you can pass the to_h
methods and convert it to a hash which is pretty neat.
[["johndoe@example.com", "John Doe"], ["janedoe@example.com", "Jane Doe"]].to_h
=> {"johndoe@example.com"=>"John Doe", "janedoe@example.com"=>"Jane Doe"}
There you have it, the Array#flatten method can take in an integer to specify the level of recursion to flatten