mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-04-11 16:00:12 -04:00
84 lines
2.1 KiB
Markdown
84 lines
2.1 KiB
Markdown
---
|
|
id: 587d7b8a367417b2b2512b4c
|
|
title: >-
|
|
Destructuring via rest elements
|
|
challengeType: 1
|
|
forumTopicId: 301218
|
|
dashedName: >-
|
|
use-destructuring-assignment-with-the-rest-parameter-to-reassign-array-elements
|
|
---
|
|
|
|
# --description--
|
|
|
|
In some situations involving array destructuring, we might want to collect the rest of the elements into a separate array.
|
|
|
|
The result is similar to `Array.prototype.slice()`, as shown below:
|
|
|
|
```js
|
|
const [a, b, ...arr] = [1, 2, 3, 4, 5, 7];
|
|
console.log(a, b);
|
|
console.log(arr);
|
|
```
|
|
|
|
The console would display the values `1, 2` and `[3, 4, 5, 7]`.
|
|
|
|
Variables `a` and `b` take the first and second values from the array. After that, because of the rest syntax presence, `arr` gets the rest of the values in the form of an array. The rest element only works correctly as the last variable in the list. As in, you cannot use the rest syntax to catch a subarray that leaves out the last element of the original array.
|
|
|
|
# --instructions--
|
|
|
|
Use a destructuring assignment with the rest syntax to emulate the behavior of `Array.prototype.slice()`. `removeFirstTwo()` should return a sub-array of the original array `list` with the first two elements omitted.
|
|
|
|
# --hints--
|
|
|
|
`removeFirstTwo([1, 2, 3, 4, 5])` should be `[3, 4, 5]`
|
|
|
|
```js
|
|
assert.deepEqual(removeFirstTwo([1, 2, 3, 4, 5]), [3, 4, 5]);
|
|
```
|
|
|
|
`removeFirstTwo()` should not modify `list`
|
|
|
|
```js
|
|
const _testArr = [1, 2, 3, 4, 5];
|
|
removeFirstTwo(_testArr);
|
|
assert.deepEqual(_testArr, [1, 2, 3, 4, 5])
|
|
```
|
|
|
|
`Array.slice()` should not be used.
|
|
|
|
```js
|
|
assert(!__helpers.removeJSComments(code).match(/\.\s*slice\s*\(/));
|
|
```
|
|
|
|
You should use the rest syntax.
|
|
|
|
```js
|
|
assert.match(code, /\.\.\./);
|
|
```
|
|
|
|
# --seed--
|
|
|
|
## --seed-contents--
|
|
|
|
```js
|
|
function removeFirstTwo(list) {
|
|
return list;
|
|
}
|
|
|
|
const source = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
|
|
const sourceWithoutFirstTwo = removeFirstTwo(source);
|
|
```
|
|
|
|
# --solutions--
|
|
|
|
```js
|
|
function removeFirstTwo(list) {
|
|
// comment with 'slice' to check comments are removed in tests
|
|
const [, , ...shorterList] = list;
|
|
return shorterList;
|
|
}
|
|
|
|
const source = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
|
|
const sourceWithoutFirstTwo = removeFirstTwo(source);
|
|
```
|