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.

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.

Interactive example available with JavaScript enabled.

Assignment

Sometimes we need to search through Textio's server logs for a specific word. Complete the splitLogs function. It searches the logs input for a message containing the slug.

When it finds one, it returns an object with 3 properties:

  • before: All the logs before the first log containing the slug (non-inclusive)
  • after: All the logs after the first log containing the slug (also non-inclusive)
  • i: The index of the first log containing the slug

If not found, just return -1 for the index and empty arrays for before and after.

The .includes() method will be useful.