* fix: rm assert msg basic-algorithm-scripting * fix: rm assert msg debugging * fix: rm assert msg es6 * fix: rm assert msg functional-programming
3.0 KiB
3.0 KiB
id, title, challengeType
id | title | challengeType |
---|---|---|
9d7123c8c441eeafaeb5bdef | Remove Elements from an Array Using slice Instead of splice | 1 |
Description
splice
method for this, which takes arguments for the index of where to start removing items, then the number of items to remove. If the second argument is not provided, the default is to remove items through the end. However, the splice
method mutates the original array it is called on. Here's an example:
var cities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
cities.splice(3, 1); // Returns "London" and deletes it from the cities array
// cities is now ["Chicago", "Delhi", "Islamabad", "Berlin"]
As we saw in the last challenge, the slice
method does not mutate the original array, but returns a new one which can be saved into a variable. Recall that the slice
method takes two arguments for the indices to begin and end the slice (the end is non-inclusive), and returns those items in a new array. Using the slice
method instead of splice
helps to avoid any array-mutating side effects.
Instructions
nonMutatingSplice
by using slice
instead of splice
. It should limit the provided cities
array to a length of 3, and return a new array with only the first three items.
Do not mutate the original array provided to the function.
Tests
tests:
- text: Your code should use the <code>slice</code> method.
testString: assert(code.match(/\.slice/g));
- text: Your code should not use the <code>splice</code> method.
testString: assert(!code.match(/\.splice/g));
- text: The <code>inputCities</code> array should not change.
testString: assert(JSON.stringify(inputCities) === JSON.stringify(["Chicago", "Delhi", "Islamabad", "London", "Berlin"]));
- text: <code>nonMutatingSplice(["Chicago", "Delhi", "Islamabad", "London", "Berlin"])</code> should return <code>["Chicago", "Delhi", "Islamabad"]</code>.
testString: assert(JSON.stringify(nonMutatingSplice(["Chicago", "Delhi", "Islamabad", "London", "Berlin"])) === JSON.stringify(["Chicago", "Delhi", "Islamabad"]));
Challenge Seed
function nonMutatingSplice(cities) {
// Add your code below this line
return cities.splice(3);
// Add your code above this line
}
var inputCities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
nonMutatingSplice(inputCities);
Solution
function nonMutatingSplice(cities) {
// Add your code below this line
return cities.slice(0,3);
// Add your code above this line
}
var inputCities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
nonMutatingSplice(inputCities);