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.
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.
Focus Editor
Alt+Shift+]
Next Tab
Alt+Shift+[
Become a member to Submit
Become a member to Run
Become a member to view solution