Slice() method question

Slice() method question
0

#1

I’m working on a challenge that utilizes .slice() so I’m fooling around with it on Repl.it to get a feel for what it does. I have a question in regard to one particular response that I think I understand but I have a sneaking suspicion that I don’t understand this.

So here is the code I’m using.

for(let i = 0; i < arr.length; i++){
var oneArr = arr.slice(i);}
return arr;
}
chunkyArrayInGroups([“a”, “b”, “c”, “d”], 2);

When I console.log (oneArr) this is what I receive:

[ 'a', 'b', 'c', 'd' ] [ 'b', 'c', 'd' ] [ 'c', 'd' ] [ 'd' ]

Why is it depreciating like that?
My guess is that it is just looping through and slicing off an element each time it iterates through the sequence.

That said, when I do this:
var oneArr = arr[i].slice(i);

My console log returns a

Why? I’m perplexed by this? Is it because it stops at the first iteration?


#2

Because that’s what slice does…

from MDN: The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end ( end not included ). The original array will not be modified.

As you loop from 0 to 3
arr.slice(0) is [ ‘a’, ‘b’, ‘c’, ‘d’ ] (index 0 to end of array)
arr.slice(1) is [ ‘b’, ‘c’, ‘d’ ]
arr.slice(2) is [ ‘c’, ‘d’ ]
arr.slice(3) is [ ‘d’ ] (index 3 to end of array)

This is all covered in detail on MDN page for array .slice() method

String has a similar slice() method.
when i is 0 arr[i] is ‘a’, a string of one character and ‘a’.slice(0) is ‘a’ (index 0 to end of string)
when i is 1 arr[i] is ‘b’ and ‘b’.slice(1) is an empty string (index 1 to end of string)

Also covered in detail by the MDN

The MDN is a great go-to manual for anyone serious about web development. Topics are explained in great detail and have accompanying examples to demonstrate key concepts. Consider it the READ part of Read-Search-Ask