callmekatootie
callmekatootie

Reputation: 11228

Array slice does not return the remaining items

As per the MDN docs, if the end parameter in Array.slice(start, end) is greater than the length of the sequence, it will extract through the end of the sequence:

If end is greater than the length of the sequence, slice extracts through to the end of the sequence (arr.length).

I have the following code:

const a = new Array(30).fill(5)

for (let i = 0; i < a.length; i += 25) {
    const newItems = a.slice(i, 25);
    console.log(newItems)
}

I get the following output:

> (25) [5, 5, 5, ... 23 items more]
> []

I am expecting the second array to be of length 5 with the remaining 5 items being captured but I get an empty array. I am not sure why though because a.slice(25, 25) should give me items that start at index 25 up to the end of the array (since it's length is less than 25). Where am I going wrong in my understanding?

Upvotes: 2

Views: 994

Answers (2)

urchmaney
urchmaney

Reputation: 618

The start and end argument for the slice function indicate the index positions in the array. Start inclusive and end excluded. The code you have is trying to use 25 as start and end. Hence the empty array maybe trying adding a count might give you your intended output.

const a = new Array(30).fill(5)

for (let i = 0; i < a.length; i += 25) {
    const newItems = a.slice(i, i + 25);
    console.log(newItems)
}

Upvotes: 0

Moti
Moti

Reputation: 583

The begin and end symbolise indexes of the array in the documentation. start is inclusive, but end is exclusive, so you are trying to retrieve slice for the following range: [25, 25) that is an empty set from the mathematical point of view.

Your code should look like this:

const a = new Array(30).fill(5)

for (let i = 0; i < a.length; i += 25) {
    const newItems = a.slice(i, i + 25);
    console.log(newItems)
}

Upvotes: 1

Related Questions