From a75d0c4bb9e20643ecb06786740442de1b5ee0f1 Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Tue, 19 Jul 2022 20:50:09 +0300 Subject: [PATCH] Add firstN and lastN --- snippets/firstN.md | 20 ++++++++++++++++++++ snippets/lastN.md | 20 ++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 snippets/firstN.md create mode 100644 snippets/lastN.md diff --git a/snippets/firstN.md b/snippets/firstN.md new file mode 100644 index 000000000..81c703f42 --- /dev/null +++ b/snippets/firstN.md @@ -0,0 +1,20 @@ +--- +title: First n elements +tags: array +expertise: beginner +author: chalarangelo +cover: blog_images/digital-nomad-16.jpg +firstSeen: 2022-07-22T05:00:00-04:00 +--- + +Gets the first `n` elements of an array. + +- Use `Array.prototype.slice()` with a start value of `0` and an end value of `n` to get the first `n` elements of `arr`. + +```js +const firstN = (arr, n) => arr.slice(0, n); +``` + +```js +firstN(['a', 'b', 'c', 'd'], 2); // ['a', 'b'] +``` diff --git a/snippets/lastN.md b/snippets/lastN.md new file mode 100644 index 000000000..0307caca7 --- /dev/null +++ b/snippets/lastN.md @@ -0,0 +1,20 @@ +--- +title: Last n elements +tags: array +expertise: beginner +author: chalarangelo +cover: blog_images/interior-5.jpg +firstSeen: 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'] +```