Start learning free

LESSON 113 OF 671 · ARRAYS I

Slicing an Array in JavaScript

Lesson

TL ; DR:

arr.slice(i, j) returns a new array with the items from index i up to, not including, j. The original array doesn't change.


let letters = ["a", "b", "c", "d", "e"];

let middle = letters.slice(1, 4);
// middle is ["b", "c", "d"]

// letters is still ["a", "b", "c", "d", "e"]


Full lesson:

Sometimes you need only part of an array, like the first few items. The slice method copies that part into a new array.

Give it the start index and the end index. The item at the end index is not included. So letters.slice(1, 4) has the items at 1, 2 and 3.

That makes the length easy to see: 4 - 1 = 3 items.

To go to the very end, use the length as the end index:

let tail = letters.slice(3, letters.length);
// tail is ["d", "e"]

You may also leave the end out. So letters.slice(3) gives the same ["d", "e"].

The original array stays as it was.

Don't mix up slice and splice. The slice method copies a part and leaves the array alone. But splice changes the array itself.


Your task

runners holds a race's runners, in the order they finished.

Put the first three in a new array named podium. Put everyone else, from index 3 to the end, in one named rest.

The code below prints both, then the length of runners.

Expected output:

Ana Ben Cleo
Dan Eve
5
STEP 1 OF 2
    Ctrl + Enter to check