Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading