union.md (1572B)
1 ---
2 title: union
3 # linktitle: union
4 description: Given two arrays or slices, returns a new array that contains the elements or objects that belong to either or both arrays/slices.
5 date: 2017-02-01
6 publishdate: 2017-02-01
7 lastmod: 2017-03-12
8 categories: [functions]
9 menu:
10 docs:
11 parent: "functions"
12 keywords: [collections,intersect,union,complement]
13 signature: ["union SET1 SET2"]
14 workson: []
15 hugoversion: 0.20
16 relatedfuncs: [intersect,where]
17 deprecated: false
18 aliases: []
19 ---
20
21 Given two arrays (or slices) A and B, this function will return a new array that contains the elements or objects that belong to either A or to B or to both. The elements supported are strings, integers, and floats (only float64).
22
23 ```
24 {{ union (slice 1 2 3) (slice 3 4 5) }}
25 <!-- returns [1 2 3 4 5] -->
26
27 {{ union (slice 1 2 3) nil }}
28 <!-- returns [1 2 3] -->
29
30 {{ union nil (slice 1 2 3) }}
31 <!-- returns [1 2 3] -->
32
33 {{ union nil nil }}
34 <!-- returns an error because both arrays/slices have to be of the same type -->
35 ```
36
37 ## OR filter in where query
38
39 This is also very useful to use as `OR` filters when combined with where:
40
41 ```
42 {{ $pages := where .Site.RegularPages "Type" "not in" (slice "page" "about") }}
43 {{ $pages := $pages | union (where .Site.RegularPages "Params.pinned" true) }}
44 {{ $pages := $pages | intersect (where .Site.RegularPages "Params.images" "!=" nil) }}
45 ```
46
47 The above fetches regular pages not of `page` or `about` type unless they are pinned. And finally, we exclude all pages with no `images` set in Page params.
48
49 See [intersect](/functions/intersect) for `AND`.