Consecutive Element Subarrays

JavaScriptJavaScriptBeginner
Practice Now

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

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28210{{"`Consecutive Element Subarrays`"}} javascript/data_types -.-> lab-28210{{"`Consecutive Element Subarrays`"}} javascript/arith_ops -.-> lab-28210{{"`Consecutive Element Subarrays`"}} javascript/comp_ops -.-> lab-28210{{"`Consecutive Element Subarrays`"}} javascript/higher_funcs -.-> lab-28210{{"`Consecutive Element Subarrays`"}} end

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 with n as the number of consecutive elements and arr as the array of numbers.
  • The function returns an array of n-tuples of consecutive elements from arr.
  • If n is greater than the length of arr, 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.

Other JavaScript Tutorials you may like