Map Consecutive Elements

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore the mapConsecutive function in JavaScript. This function allows us to map consecutive elements of an array using a given function. We will learn how to use this function to manipulate arrays in a concise and efficient way.


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-28479{{"`Map Consecutive Elements`"}} javascript/data_types -.-> lab-28479{{"`Map Consecutive Elements`"}} javascript/arith_ops -.-> lab-28479{{"`Map Consecutive Elements`"}} javascript/comp_ops -.-> lab-28479{{"`Map Consecutive Elements`"}} javascript/higher_funcs -.-> lab-28479{{"`Map Consecutive Elements`"}} end

Function to Map Consecutive Elements in an Array

To start coding, open the Terminal/SSH and type node.

This function maps each block of n consecutive elements in an array, using the given function fn. Follow these steps:

  • Use Array.prototype.slice() to obtain a new array arr with the first n elements removed.
  • Use Array.prototype.map() and Array.prototype.slice() to apply fn to each block of n consecutive elements in arr.

Here's the code:

const mapConsecutive = (arr, n, fn) =>
  arr.slice(n - 1).map((v, i) => fn(arr.slice(i, i + n)));

For example, you can use mapConsecutive() to map each block of 3 consecutive elements in an array of numbers, joining them with dashes:

mapConsecutive([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3, (x) => x.join("-"));
// ['1-2-3', '2-3-4', '3-4-5', '4-5-6', '5-6-7', '6-7-8', '7-8-9', '8-9-10'];

Summary

Congratulations! You have completed the Map Consecutive Elements lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like