Files
30-seconds-of-code/snippets/js/s/last-n-elements.md
Angelos Chalaris 9d032ce05e Rename js snippets
2023-05-19 20:23:47 +03:00

22 lines
407 B
Markdown

---
title: Last n elements
type: snippet
language: javascript
tags: [array]
author: chalarangelo
cover: fort-lamp
dateModified: 2022-07-23T05:00:00-04:00
---
Gets the last `n` elements of an array.
- Use `Array.prototype.slice()` with a start value of `-n` to get the last `n` elements of `arr`.
```js
const lastN = (arr, n) => arr.slice(-n);
```
```js
lastN(['a', 'b', 'c', 'd'], 2); // ['c', 'd']
```