Introduction
In this lab, we will explore how to find all arrays of consecutive elements in a given array using JavaScript. We will learn how to use Array.prototype.slice() and Array.prototype.map() methods to extract and map elements of an array to create arrays of n consecutive elements. This lab will help you improve your understanding of JavaScript array manipulation and functional programming concepts.
Finding Arrays of Consecutive Elements
To find arrays of consecutive elements, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
Array.prototype.slice()to create an array withn - 1elements removed from the start. - Use
Array.prototype.map()andArray.prototype.slice()to map each element to an array ofnconsecutive elements.
Here's an example function that implements these steps:
const findConsecutive = (arr, n) =>
arr.slice(n - 1).map((v, i) => arr.slice(i, i + n));
You can call this function with an array and a number n to find all arrays of n consecutive elements in the array. For example:
findConsecutive([1, 2, 3, 4, 5], 2);
// [[1, 2], [2, 3], [3, 4], [4, 5]]
Summary
Congratulations! You have completed the Arrays of Consecutive Elements lab. You can practice more labs in LabEx to improve your skills.