--- url: "https://martinfowler.com/articles/collection-pipeline/flatten.html" titulek: "flatten" h1: "flatten" popis: "" jazyk: "" kanonicka: "" drobecky: [] zdroj: "live" wayback_snapshot: "" stazeno: "2026-09-14 00:35:15" znaku: 1167 slov: 206 kodovani: "utf-8" sha256: "8b3217a906e70a544010be7c4c0c857a2578be8ff1e156ebd6a5ee9e7493a5f5" --- This page describes an operation in the collection pipeline pattern. For more context read: - [Collection Pipeline Article](/articles/collection-pipeline) : An article explaining the collection pipeline pattern - [Operation Catalog](/articles/collection-pipeline#op-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](flat-map.html) to do this combo. If you need a single-level flatten you can use [flat-map](flat-map.html) 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) ```