2018-09-30 23:01:58 +01:00
---
id: 587d7b7a367417b2b2512b12
title: Copy Array Items Using slice()
challengeType: 1
2019-08-05 09:17:33 -07:00
forumTopicId: 301158
2021-01-13 03:31:00 +01:00
dashedName: copy-array-items-using-slice
2018-09-30 23:01:58 +01:00
---
2020-11-27 19:02:05 +01:00
# --description--
The next method we will cover is `slice()` . Rather than modifying an array, `slice()` copies or *extracts* a given number of elements to a new array, leaving the array it is called upon untouched. `slice()` takes only 2 parameters — the first is the index at which to begin extraction, and the second is the index at which to stop extraction (extraction will occur up to, but not including the element at this index). Consider this:
2019-04-26 17:21:49 -07:00
2019-05-01 09:33:02 -07:00
```js
2019-04-26 17:21:49 -07:00
let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];
let todaysWeather = weatherConditions.slice(1, 3);
```
2021-03-02 16:12:12 -08:00
`todaysWeather` would have the value `['snow', 'sleet']` , while `weatherConditions` would still have `['rain', 'snow', 'sleet', 'hail', 'clear']` .
2018-09-30 23:01:58 +01:00
In effect, we have created a new array by extracting elements from an existing array.
2020-11-27 19:02:05 +01:00
# --instructions--
2021-03-02 16:12:12 -08:00
We have defined a function, `forecast` , that takes an array as an argument. Modify the function using `slice()` to extract information from the argument array and return a new array that contains the string elements `warm` and `sunny` .
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --hints--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
`forecast` should return `["warm", "sunny"]`
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
assert.deepEqual(
forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']),
['warm', 'sunny']
);
2018-09-30 23:01:58 +01:00
```
2020-11-27 19:02:05 +01:00
The `forecast` function should utilize the `slice()` method
```js
assert(/\.slice\(/.test(code));
```
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --seed--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
## --seed-contents--
2018-09-30 23:01:58 +01:00
```js
function forecast(arr) {
2020-03-02 23:18:30 -08:00
// Only change code below this line
2018-10-08 01:01:53 +01:00
2018-09-30 23:01:58 +01:00
return arr;
}
2020-03-02 23:18:30 -08:00
// Only change code above this line
2018-09-30 23:01:58 +01:00
console.log(forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']));
```
2020-11-27 19:02:05 +01:00
# --solutions--
2018-09-30 23:01:58 +01:00
```js
2019-04-10 08:33:15 -07:00
function forecast(arr) {
return arr.slice(2,4);
}
2018-09-30 23:01:58 +01:00
```