Introduction
In this lab, we will explore the concept of creating consecutive element subarrays using JavaScript. The goal of this lab is to learn how to create an array of n-tuples of consecutive elements using the Array.prototype.slice() and Array.prototype.map() methods in JavaScript. Through practical examples, we will understand how to populate the array with n-tuples of consecutive elements from an input array and return an empty array if n is greater than the length of the input array.
Consecutive Element Subarrays
To practice coding, open the Terminal/SSH and type node. The following code creates an array of n-tuples of consecutive elements.
const aperture = (n, arr) =>
n > arr.length ? [] : arr.slice(n - 1).map((v, i) => arr.slice(i, i + n));
To use the function:
- Call
aperture(n, arr)function withnas the number of consecutive elements andarras the array of numbers. - The function returns an array of
n-tuples of consecutive elements fromarr. - If
nis greater than the length ofarr, the function returns an empty array.
Example usage:
aperture(2, [1, 2, 3, 4]); // [[1, 2], [2, 3], [3, 4]]
aperture(3, [1, 2, 3, 4]); // [[1, 2, 3], [2, 3, 4]]
aperture(5, [1, 2, 3, 4]); // []
Summary
Congratulations! You have completed the Consecutive Element Subarrays lab. You can practice more labs in LabEx to improve your skills.