Slicing & Splicing

Copy part of an array with slice, or edit it with splice.

Syntaxarr.slice(1, 3) arr.splice(1, 2)

Two similarly named methods do very different things:

  • slice(start, end) β€” returns a copy of part of the array. It does not change the original.
  • splice(start, count, ...items) β€” changes the array by removing and/or inserting items.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Extract the first five results from a search array to show as a preview on the landing page.
  • Copy a subset of log entries between two timestamps for display in a paginated log viewer.
  • Clone an array without mutating the original before passing it to a sorting function.

More examples

Slice first N items

Uses slice(0, 3) to extract the first three items as a preview without modifying the original array.

Example Β· js
const results = ["A", "B", "C", "D", "E", "F"];
const preview = results.slice(0, 3);
console.log(preview); // ["A", "B", "C"]

Slice a page of results

Computes start and end offsets from a page number and page size to slice a single page of data.

Example Β· js
const all = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const page = 2;
const size = 3;
const pageData = all.slice((page - 1) * size, page * size);
console.log(pageData); // [4, 5, 6]

Clone an array with slice

Clones an array with slice() before sorting so the original order is preserved.

Example Β· js
const original = [3, 1, 4, 1, 5];
const copy = original.slice();
copy.sort((a, b) => a - b);
console.log(original); // [3, 1, 4, 1, 5] – unchanged
console.log(copy);     // [1, 1, 3, 4, 5]

Discussion

  • Be the first to comment on this lesson.
Slicing & Splicing β€” JavaScript | SoundsCode