Menu
Coddy logo textTech

Array Slicing

Part of the Fundamentals section of Coddy's JavaScript journey — lesson 67 of 77.

Slicing allows us to extract portions of an array using the following syntax: arr.slice(start, stop). For example, consider this array:

let numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

Getting a portion of the array:

console.log(numbers.slice(2, 6));
// Output: [2, 3, 4, 5]

This gets elements from index 2 (inclusive) to index 6 (exclusive)

Omitting stop parameter:

console.log(numbers.slice(5));
// Output: [5, 6, 7, 8, 9]

When stop is omitted, slice goes until the end

challenge icon

Challenge

Easy

Create a program that receives an array as input (given) and prints the following sliced arrays:

  • For odd-length arrays: take the middle item and one item on each side (3 items total)
  • For even-length arrays: take the two middle items

For this challenge, use Math.floor() because array slicing only works with whole numbers.

Example, Math.floor(5.5) will return 5 as it find the floor of a float number

Try it yourself

let arr = inp.split(", ").map(Number);
// Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals