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
Set vi as the default editor in Ubuntu — a terminal opening the vim editor
How to Set vi (Vim) as the Default Editor in Ubuntu
June 8, 2026
rsync says ALL DONE but files are missing — a terminal showing ALL DONE next to an empty folder
rsync Says “ALL DONE” but Files Are Missing: How to Verify
June 8, 2026
Migrate a website to a new server with rsync — files copying from an old server to a new one over SSH
How to Migrate a Website to a New Server With rsync
June 8, 2026
Bun runtime — faster JS toolkit replacing npm in Laravel projects
How to Install Bun Runtime on Ubuntu (And Use It in a Laravel Project)
May 24, 2026
Tailscale mesh — peer-to-peer connections between devices, coordination server
How to Install Tailscale on Ubuntu (Zero-Config Mesh VPN for Self-Hosters)
May 24, 2026

You Might Also Like

Open a file selection dialog from a button click
Web Development

How to Open a File Dialog When Clicking a Button

4 Min Read
Laravel DataTables custom column search — filterColumn callback handles the search SQL
Web Development

How to Search Custom or Composite Columns in Laravel DataTables

8 Min Read
WordPress login user programmatically — wp_set_current_user plus wp_set_auth_cookie
Web Development

How to Login a User Programmatically in WordPress

8 Min Read
Laravel migration adding two new columns to an existing transactions table
Web Development

How to Add New Columns to an Existing Table in Laravel Migration

5 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?