Arrays of Consecutive Elements

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use Array.prototype.slice() to create an array with n - 1 elements removed from the start.
  3. Use Array.prototype.map() and Array.prototype.slice() to map each element to an array of n consecutive 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.