1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-02 22:58:01 +00:00

Add Get The Last Item From An Array as a jq TIL

This commit is contained in:
jbranchaud
2024-01-14 14:34:35 -06:00
parent 83fddacd29
commit 63097d0feb
2 changed files with 24 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1363 TILs and counting..._
_1364 TILs and counting..._
---
@@ -512,6 +512,7 @@ _1363 TILs and counting..._
- [Find All Objects In An Array Where Key Is Set](jq/find-all-objects-in-an-array-where-key-is-set.md)
- [Find All Objects With A Matching Key Value Pair](jq/find-all-objects-with-a-matching-key-value-pair.md)
- [Get The First Item For Every Top-Level Key](jq/get-the-first-item-for-every-top-level-key.md)
- [Get The Last Item From An Array](jq/get-the-last-item-from-an-array.md)
- [Reduce Object To Just Entries Of A Specific Type](jq/reduce-object-to-just-entries-of-a-specific-type.md)
- [Turn A List From A Command Into JSON](jq/turn-a-list-from-a-command-into-json.md)
- [Zip Two JSON Files Together Based On Shared ID](jq/zip-two-json-files-together-based-on-shared-id.md)

View File

@@ -0,0 +1,22 @@
# Get The Last Item From An Array
There are two ways to get the last item from an array using
[`jq`](https://jqlang.github.io/jq/).
The one that is perhaps a bit more intuitive is to pipe the array to the
[`last`](https://jqlang.github.io/jq/manual/#first-last-nth-2) function.
```bash
$ echo '[1,2,3]' | jq '. | last'
3
```
Another approach is to use an [array index
expression](https://jqlang.github.io/jq/manual/#array-index) to positionally
grab the last element of the array. As is the case with some languages and
libraries, `-1` positionally refers to the last item in the array.
```bash
$ echo '[1,2,3]' | jq '.[-1]'
3
```