2018-10-12 15:37:13 -04:00
|
|
|
---
|
|
|
|
title: Remove Elements from an Array Using slice Instead of splice
|
|
|
|
---
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
# Remove Elements from an Array Using slice Instead of splice
|
|
|
|
|
|
|
|
---
|
|
|
|
## Problem Explanation
|
2018-10-12 15:37:13 -04:00
|
|
|
- The difference between splice and slice method is that the slice method does not mutate the original array, but returns a new one.
|
|
|
|
- The slice method takes 2 two arguments for the indices to begin and end the slice (the end is non-inclusive).
|
|
|
|
- If you do not want to mutate the original array, you can use the slice method.
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
---
|
|
|
|
## Solutions
|
|
|
|
|
|
|
|
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
|
|
|
|
2018-10-12 15:37:13 -04:00
|
|
|
```javascript
|
|
|
|
function nonMutatingSplice(cities) {
|
|
|
|
// Add your code below this line
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
return cities.slice(0, 3);
|
|
|
|
|
2018-10-12 15:37:13 -04:00
|
|
|
// Add your code above this line
|
|
|
|
}
|
|
|
|
var inputCities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
|
|
|
|
nonMutatingSplice(inputCities);
|
|
|
|
```
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
</details>
|