Debian Codegraph @

docs/content/en/functions/collections/Complement.md

raw
1 ---
2 title: collections.Complement
3 description: Returns a slice by identifying elements in the last given slice that do not appear in any of the preceding slices.
4 categories: []
5 keywords: []
6 params:
7 functions_and_methods:
8 aliases: [complement]
9 returnType: '[]any'
10 signatures: ['collections.Complement SLICE [SLICE...]']
11 aliases: [/functions/complement]
12 ---
13
14 To find the elements within `$c3` that do not exist in `$c1` or `$c2`:
15
16 ```go-html-template
17 {{ $c1 := slice 3 }}
18 {{ $c2 := slice 4 5 }}
19 {{ $c3 := slice 1 2 3 4 5 }}
20
21 {{ complement $c1 $c2 $c3 }} → [1 2]
22 ```
23
24 > [!NOTE]
25 > Make your code simpler to understand by using a [chained pipeline][]:
26
27 ```go-html-template
28 {{ $c3 | complement $c1 $c2 }} → [1 2]
29 ```
30
31 You can also use the `complement` function with page collections. Let's say your site has five content types:
32
33 ```tree
34 content/
35 ├── blog/
36 ├── books/
37 ├── faqs/
38 ├── films/
39 └── songs/
40 ```
41
42 To list everything except blog articles (`blog`) and frequently asked questions (`faqs`):
43
44 ```go-html-template
45 {{ $blog := where site.RegularPages "Type" "blog" }}
46 {{ $faqs := where site.RegularPages "Type" "faqs" }}
47 {{ range site.RegularPages | complement $blog $faqs }}
48 <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
49 {{ end }}
50 ```
51
52 > [!NOTE]
53 > Although the example above demonstrates the `complement` function, you could use the [`where`][] function as well:
54
55 ```go-html-template
56 {{ range where site.RegularPages "Type" "not in" (slice "blog" "faqs") }}
57 <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
58 {{ end }}
59 ```
60
61 In this example we use the `complement` function to remove [stop words][] from a sentence:
62
63 ```go-html-template
64 {{ $text := "The quick brown fox jumps over the lazy dog" }}
65 {{ $stopWords := slice "a" "an" "in" "over" "the" "under" }}
66 {{ $filtered := split $text " " | complement $stopWords }}
67
68 {{ delimit $filtered " " }} → The quick brown fox jumps lazy dog
69 ```
70
71 [`where`]: /functions/collections/where/
72 [chained pipeline]: https://pkg.go.dev/text/template#hdr-Pipelines
73 [stop words]: https://en.wikipedia.org/wiki/Stop_word