We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Slicing Arrays

JavaScript's .slice method makes it easy to, well, slice and dice arrays:

const animals = ["ant", "bison", "camel", "duck", "elephant"];
console.log(animals.slice(2));
// ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// ["camel", "duck"]
console.log(animals.slice(1, 5));
// ["bison", "camel", "duck", "elephant"]
console.log(animals.slice(-2));
// ["duck", "elephant"]
console.log(animals.slice(2, -1));
// ["camel", "duck"]
console.log(animals.slice());
// ["ant", "bison", "camel", "duck", "elephant"]

The first argument is the starting index, and the second argument is the ending index (exclusive). If the second argument is omitted, the slice goes to the end of the array.

Slicing returns a new array without changing the original. If a slice asks for more elements than exist, it includes only the available elements.

JavaScript doesn't support negative indexing directly into arrays (like animals[-1]), but the slice() method does support negative indexes.

In slice(), -1 means the last element, -2 means the second-to-last, and so on.

Sequence Slicing

Adjust the slice controls and watch values move into the result.
stop
start
champions.slice(0, 2)

champions.slice(0, 2) returns [Frodo, Aragorn].

Assignment

Textio's log viewer needs a few views of the same logs. Complete getLogViews using .slice(). It takes a logs array and returns an object with three properties:

  • preview: The first three logs, or all logs if there are fewer than three.

  • remaining: All logs after the first three.

  • recent: The last two logs, or all logs if there are fewer than two.