2019-10-21 04:22:28 -04:00
|
|
|
---
|
2023-10-20 03:42:39 -04:00
|
|
|
title: collections.First
|
|
|
|
linkTitle: first
|
|
|
|
description: Slices an array to the first N elements.
|
2019-10-21 04:22:28 -04:00
|
|
|
categories: [functions]
|
2023-10-20 03:42:39 -04:00
|
|
|
keywords: []
|
2019-10-21 04:22:28 -04:00
|
|
|
menu:
|
|
|
|
docs:
|
2023-05-22 10:43:12 -04:00
|
|
|
parent: functions
|
2023-10-20 03:42:39 -04:00
|
|
|
function:
|
|
|
|
aliases: [first]
|
|
|
|
returnType: any
|
|
|
|
signatures: [collections.First LIMIT COLLECTION]
|
|
|
|
relatedFunctions:
|
|
|
|
- collections.After
|
|
|
|
- collections.First
|
|
|
|
- collections.Last
|
|
|
|
aliases: [/functions/first]
|
2019-10-21 04:22:28 -04:00
|
|
|
---
|
|
|
|
|
|
|
|
`first` works in a similar manner to the [`limit` keyword in
|
|
|
|
SQL][limitkeyword]. It reduces the array to only the `first N`
|
|
|
|
elements. It takes the array and number of elements as input.
|
|
|
|
|
|
|
|
`first` takes two arguments:
|
|
|
|
1. `number of elements`
|
|
|
|
2. `array` *or* `slice of maps or structs`
|
|
|
|
|
|
|
|
{{< code file="layout/_default/section.html" >}}
|
|
|
|
{{ range first 10 .Pages }}
|
|
|
|
{{ .Render "summary" }}
|
|
|
|
{{ end }}
|
|
|
|
{{< /code >}}
|
|
|
|
|
|
|
|
*Note: Exclusive to `first`, LIMIT can be '0' to return an empty array.*
|
|
|
|
|
|
|
|
## `first` and `where` Together
|
|
|
|
|
2023-10-20 03:42:39 -04:00
|
|
|
Using `first` and [`where`] together can be very
|
|
|
|
powerful. Below snippet gets a list of posts only from [main
|
|
|
|
sections], sorts it by the `title` parameter, and then
|
2019-10-21 04:22:28 -04:00
|
|
|
ranges through only the first 5 posts in that list:
|
|
|
|
|
|
|
|
{{< code file="first-and-where-together.html" >}}
|
|
|
|
{{ range first 5 (where site.RegularPages "Type" "in" site.Params.mainSections).ByTitle }}
|
|
|
|
{{ .Content }}
|
|
|
|
{{ end }}
|
|
|
|
{{< /code >}}
|
|
|
|
|
|
|
|
|
|
|
|
[limitkeyword]: https://www.techonthenet.com/sql/select_limit.php
|
2023-10-20 03:42:39 -04:00
|
|
|
[`where`]: /functions/collections/where
|
|
|
|
[main sections]: /functions/collections/where#mainsections
|