How7o
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Reading: How to Get N Elements from an Array in JavaScript
Share
How7oHow7o
Font ResizerAa
  • OS
Search
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Follow US
© 2024–2026 How7o. All rights reserved.
How7o > Free Laravel, PHP, WordPress & Server Tutorials > Web Development > How to Get N Elements from an Array in JavaScript
Web Development

How to Get N Elements from an Array in JavaScript

how7o
By how7o
Last updated: May 22, 2026
5 Min Read
Get N elements from a JavaScript array with slice for pagination
SHARE

To get N elements from an array in JavaScript, use Array.prototype.slice(start, end). It returns a shallow copy of the items at indices start through end - 1 — the end is exclusive. For pagination, the formula is arr.slice((page - 1) * perPage, page * perPage).

Contents
  • Pagination with slice()
  • slice() arguments
  • Pagination + total page count
  • slice() doesn’t modify the original
  • Frequently asked questions
  • Related guides
  • References

Last verified: 2026-05-17 in Chrome 124, Firefox 125, Safari 17. Originally published 2022-07-23, rewritten and updated 2026-05-17.

Pagination with slice()

const listItems = [/* item1, item2, ..., item100 */];

function pageItems(arr, page, perPage = 10) {
    const start = (page - 1) * perPage;
    const end   =  page      * perPage;
    return arr.slice(start, end);
}

// Page 1 -> items at indices 0..9
pageItems(listItems, 1);

// Page 3 -> items at indices 20..29
pageItems(listItems, 3);

The standard formula: start at (page - 1) * perPage, end at page * perPage. Page numbers are 1-based (page 1 = first page); array indices are 0-based; slice‘s end is exclusive — that’s why the same multiplier works.

JS array slice for pagination — start/end formula, negative indices, last-N helper

slice() arguments

  • arr.slice(0, 10) — first 10 items (indices 0–9).
  • arr.slice(10) — from index 10 to the end. Omit end to mean “to the end.”
  • arr.slice(-5) — last 5 items (negative counts from the end).
  • arr.slice(-10, -5) — items at 10-from-end through 6-from-end.
  • arr.slice() — full shallow copy of the array.

Pagination + total page count

function paginate(arr, page, perPage = 10) {
    const totalPages = Math.ceil(arr.length / perPage);
    const clamped    = Math.min(Math.max(page, 1), totalPages);
    const start      = (clamped - 1) * perPage;

    return {
        page:       clamped,
        totalPages,
        items:      arr.slice(start, start + perPage),
    };
}

const { items, page, totalPages } = paginate(listItems, 3);
console.log(`Page ${page} of ${totalPages}`, items);

Clamp the requested page to the valid range so out-of-bounds page numbers (negative, zero, or past the last page) don’t return empty arrays.

slice() doesn’t modify the original

const original = [1, 2, 3, 4, 5];
const firstTwo = original.slice(0, 2);

console.log(firstTwo); // [1, 2]
console.log(original); // [1, 2, 3, 4, 5]  — unchanged

slice() is non-destructive. (Don’t confuse it with splice() — different method, mutates the array.)

Frequently asked questions

Is the second argument to slice() inclusive or exclusive?

Exclusive. arr.slice(0, 10) returns items at index 0 through 9 — ten items total. That’s why the pagination formula is slice((page - 1) * perPage, page * perPage): the end index is one past the last item you want.

What’s the difference between slice() and splice()?

slice() returns a copy and leaves the original alone. splice() mutates the array — it inserts and/or removes items in place and returns the removed ones. For pagination you want a non-destructive read, so slice() is the right call. Mixing them up is a common bug.

Negative indices — what do they do?

Negative numbers count from the end. arr.slice(-3) returns the last three items; arr.slice(-5, -2) returns items 5-from-the-end through 3-from-the-end. Negative indices are great for “the last N items” patterns but rarely useful for paginated views, which usually expect forward-counting.

Should I paginate the array client-side or fetch one page at a time from a server?

For arrays under a few thousand items, client-side slice() is simpler, faster (no extra requests), and lets users navigate instantly. For larger datasets, fetch one page at a time — the server returns just the slice, and your client uses the same indexing logic to render it. The break-even point depends on row size, but tens of thousands of objects in memory usually justifies server-side.

Related guides

  • How to Create Ajax-Based Pagination in DataTables
  • How to Get the Index in a jQuery .each() Loop
  • How to Break Out of a jQuery .each() Loop

References

MDN Array.prototype.slice(): developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice. MDN Array.prototype.splice(): developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice.

TAGGED:arraysJavaScript

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
[mc4wp_form]
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Previous Article WordPress wpdb get_results returns multiple rows How to Get Multiple Rows with $wpdb in WordPress
Next Article Remove the Other Favorites button on the Microsoft Edge favorites bar How to Remove the “Other Favorites” Button in Microsoft Edge
Leave a Comment

Leave a Reply Cancel reply

You must be logged in to post a comment.

FacebookLike
XFollow
PinterestPin
InstagramFollow
Most Popular
Run Laravel queue workers with Supervisor
How to Run Laravel Queue Workers in Production with Supervisor
May 23, 2026
Nginx as a reverse proxy for a Node.js app on Ubuntu
How to Set Up Nginx as a Reverse Proxy for Node.js on Ubuntu
May 23, 2026
Install and configure Redis on Ubuntu for Laravel and WordPress
How to Install and Configure Redis on Ubuntu (for Laravel & WordPress)
May 23, 2026
Harden a fresh Ubuntu VPS with UFW, Fail2Ban, and SSH key auth
How to Harden a Fresh Ubuntu VPS: UFW + Fail2Ban + SSH Key Auth
May 23, 2026
Set up Let's Encrypt SSL with Certbot on Ubuntu
How to Set Up Let’s Encrypt SSL with Certbot on Ubuntu (Apache & Nginx)
May 23, 2026

You Might Also Like

Laravel Eloquent exists method checking if a record exists in a database query
Web Development

How to Check if a Record Exists in Laravel

6 Min Read
Select all text in a contenteditable div on click
Web Development

How to Select All Text in a Contenteditable Div on Click

4 Min Read
Replace jQuery .each with vanilla JavaScript loops
Web Development

How to Replace jQuery’s .each() with Vanilla JavaScript

4 Min Read
MySQL 8 create user and grant privileges on Ubuntu
Web Development

How to Create Users and Grant Privileges in MySQL 8 on Ubuntu

8 Min Read
How7o

We provide tips, tricks, and advice for improving websites and doing better search.

Tools

  • Age Calculator
  • Word Counter
  • Image Upscaler
  • Password Generator
  • QR Code Generator
  • See all tools→

Pranks

  • Fake Blue Screen Prank
  • Hacker Typer
  • Fake iMessage Generator
  • Windows XP Crash Prank
  • Windows 11 Update Prank
  • See all prank screens →

Company

  • About Us
  • Blog
  • Contact
  • Privacy Policy
  • Terms of Service
  • Sitemap
© 2024–2026 How7o. All rights reserved.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?