2.1 KiB
2.1 KiB
id, title, challengeType
id | title | challengeType |
---|---|---|
587d7b7a367417b2b2512b12 | Copy Array Items Using slice() | 1 |
Description
slice()
. slice()
, rather than modifying an array, 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:
let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];
let todaysWeather = weatherConditions.slice(1, 3);
// todaysWeather equals ['snow', 'sleet'];
// weatherConditions still equals ['rain', 'snow', 'sleet', 'hail', 'clear']
In effect, we have created a new array by extracting elements from an existing array.
Instructions
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 elements 'warm'
and 'sunny'
.
Tests
tests:
- text: <code>forecast</code> should return <code>["warm", "sunny"]</code>
testString: assert.deepEqual(forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']), ['warm', 'sunny']);
- text: The <code>forecast</code> function should utilize the <code>slice()</code> method
testString: assert(/\.slice\(/.test(code));
Challenge Seed
function forecast(arr) {
// change code below this line
return arr;
}
// do not change code below this line
console.log(forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']));
Solution
function forecast(arr) {
return arr.slice(2,4);
}