JavaScript Interview Question #29: Slice and dice
source link: https://dev.to/coderslang/javascript-interview-question-29-slice-and-dice-16fk
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Test your JavaScript skills (29 Part Series)
What's happened to arr
?
Array.slice
in JavaScript returns the shallow copy of the array. The start
and end
indices should be supplied to it as the first 2 parameters. The element at arr[start]
is included in the copy, and the element at arr[end]
is not.
Contrary to Array.splice
, the original array won’t be modified when we use Array.slice
.
So, after the first 2 lines of code, we’ll get the following state:
[ 1, 2, 3, 4, 5] // arr
[ 2 ] // slicedArr
Then, we do two actions under arr.splice
:
- we remove 2 elements from
arr
starting atarr[1]
. So the original array becomes is[ 1, 4, 5 ]
at this point. - we destructure
…slicedArr
and insert its elements intoarr
starting atarr[1]
. This way we’ll get to our final state[ 1, 2, 4, 5]
inarr
.
Here’s a code snippet with additional logging:
const arr = [1, 2, 3, 4, 5];
const slicedArr = arr.slice(1, 2);
console.log(arr); // [ 1, 2, 3, 4, 5]
console.log(slicedArr); // [ 2 ]
arr.splice(1, 2, ...slicedArr);
console.log(arr); // [ 1, 2, 4, 5]
ANSWER: The original array arr
will be modified and hold values [ 1, 2, 4, 5]
.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK