This page describes an operation in the collection pipeline pattern. For more context read:
- Collection Pipeline Article: An article explaining the collection pipeline pattern
- Operation Catalog: The list of selected operations that I have these pages for.
flatten
Removes nesting from a collection
Flatten removes nesting within a collection.
ruby…
[[1,2, [3,4], 5], 6, [7,8]].flatten # => [1, 2, 3, 4, 5, 6, 7, 8]
clojure…
(flatten [[1 2 [3 4] 5] 6 [7 8]]) ;; => (1 2 3 4 5 6 7 8)
The full flattening removes all amounts of nesting. Some versions allow you to remove a limited depth of nesting with an argument
ruby…[[1,2, [3,4], 5], 6, [7,8]].flatten(1) # => [1, 2, [3, 4], 5, 6, 7, 8]
It's fairly common to remove a single level of nesting like this after a map. So common, that there's you often see the operator flat-map to do this combo.
If you need a single-level flatten you can use flat-map to get there.
clojure…(defn flatten-1 [c] (mapcat #(if (coll? %) % [%]) c)) (flatten-1 [[1 2 [3 4] 5] 6 [7 8]]) ;; => (1 2 [3 4] 5 6 7 8)