File: Complement.md

package info (click to toggle)
hugo 0.131.0-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 45,580 kB
  • sloc: javascript: 31,172; xml: 248; makefile: 73; sh: 42
file content (80 lines) | stat: -rw-r--r-- 2,188 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
---
title: collections.Complement
description: Returns the elements of the last collection that are not in any of the others.
categories: []
keywords: []
action:
  aliases: [complement]
  related:
    - functions/collections/Intersect
    - functions/collections/SymDiff
    - functions/collections/Union
  returnType: any
  signatures: ['collections.Complement COLLECTION [COLLECTION...]']
aliases: [/functions/complement]
---

To find the elements within `$c3` that do not exist in `$c1` or `$c2`:

```go-html-template
{{ $c1 := slice 3 }}
{{ $c2 := slice 4 5 }}
{{ $c3 := slice 1 2 3 4 5 }}

{{ complement $c1 $c2 $c3 }} → [1 2]
```

{{% note %}}
Make your code simpler to understand by using a [chained pipeline]:

[chained pipeline]: https://pkg.go.dev/text/template#hdr-Pipelines
{{% /note %}}

```go-html-template
{{ $c3 | complement $c1 $c2 }} → [1 2]
```

You can also use the `complement` function with page collections. Let's say your site has five content types:

```text
content/
├── blog/
├── books/
├── faqs/
├── films/
└── songs/
```

To list everything except blog articles (`blog`) and frequently asked questions (`faqs`):

```go-html-template
{{ $blog := where site.RegularPages "Type" "blog" }}
{{ $faqs := where site.RegularPages "Type" "faqs" }}
{{ range site.RegularPages | complement $blog $faqs }}
  <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
{{ end }}
```

{{% note %}}
Although the example above demonstrates the `complement` function, you could use the [`where`] function as well:

[`where`]: /functions/collections/where/
{{% /note %}}

```go-html-template
{{ range where site.RegularPages "Type" "not in" (slice "blog" "faqs") }}
  <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
{{ end }}
```

In this example we use the `complement` function to remove [stop words] from a sentence:

```go-html-template
{{ $text := "The quick brown fox jumps over the lazy dog" }}
{{ $stopWords := slice "a" "an" "in" "over" "the" "under" }}
{{ $filtered := split $text " " | complement $stopWords }}

{{ delimit $filtered " " }} → The quick brown fox jumps lazy dog
```

[stop words]: https://en.wikipedia.org/wiki/Stop_word