6

JavaScript Interview Question #29: Slice and dice

 3 years ago
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.
neoserver,ios ssh client

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
Enter fullscreen modeExit fullscreen mode

Then, we do two actions under arr.splice:

  • we remove 2 elements from arr starting at arr[1]. So the original array becomes is [ 1, 4, 5 ] at this point.
  • we destructure …slicedArr and insert its elements into arr starting at arr[1]. This way we’ll get to our final state [ 1, 2, 4, 5] in arr.

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]
Enter fullscreen modeExit fullscreen mode

ANSWER: The original array arr will be modified and hold values [ 1, 2, 4, 5].

Learn Full-Stack JavaScript


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK