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
EasyCreate 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
Cheat sheet
Use arr.slice(start, stop) to extract portions of an array:
let numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(numbers.slice(2, 6)); // [2, 3, 4, 5]The start index is inclusive, the stop index is exclusive.
Omit the stop parameter to slice until the end:
console.log(numbers.slice(5)); // [5, 6, 7, 8, 9]Use Math.floor() to convert floats to whole numbers for array indexing:
Math.floor(5.5); // returns 5Try it yourself
let arr = inp.split(", ").map(Number);
// Write your code belowThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Type Coercion7Bill Split Calculator
Welcome MessageCalculating The Tip And Total2Variables
NumbersStringBooleanNaming ConventionsEmpty VariablesRecap - Initialize VariablesConstants3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsStrict vs Loose EqualityRecap - Simple Math6Basic IO
OutputOutput with VariablesType Conversion - Part 1Type Conversion - Part 2Recap - Till 120Recap - True or False