Rename js snippets
This commit is contained in:
23
snippets/js/s/offset-array-elements.md
Normal file
23
snippets/js/s/offset-array-elements.md
Normal file
@ -0,0 +1,23 @@
|
||||
---
|
||||
title: Offset array elements
|
||||
type: snippet
|
||||
language: javascript
|
||||
tags: [array]
|
||||
cover: interior-10
|
||||
dateModified: 2020-10-21T21:54:53+03:00
|
||||
---
|
||||
|
||||
Moves the specified amount of elements to the end of the array.
|
||||
|
||||
- Use `Array.prototype.slice()` twice to get the elements after the specified index and the elements before that.
|
||||
- Use the spread operator (`...`) to combine the two into one array.
|
||||
- If `offset` is negative, the elements will be moved from end to start.
|
||||
|
||||
```js
|
||||
const offset = (arr, offset) => [...arr.slice(offset), ...arr.slice(0, offset)];
|
||||
```
|
||||
|
||||
```js
|
||||
offset([1, 2, 3, 4, 5], 2); // [3, 4, 5, 1, 2]
|
||||
offset([1, 2, 3, 4, 5], -2); // [4, 5, 1, 2, 3]
|
||||
```
|
||||
Reference in New Issue
Block a user