Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

240
Views
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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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)
}
about 4 years ago · Juan Pablo Isaza Report

0

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)
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!