Every NTH Element

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore the concept of higher-order functions in JavaScript. We will learn how to use built-in higher-order functions such as map(), filter(), and reduce() to manipulate and transform arrays. By the end of this lab, you will have a solid understanding of higher-order functions and be able to apply them in your own JavaScript projects.


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-28290{{"`Every NTH Element`"}} javascript/data_types -.-> lab-28290{{"`Every NTH Element`"}} javascript/arith_ops -.-> lab-28290{{"`Every NTH Element`"}} javascript/comp_ops -.-> lab-28290{{"`Every NTH Element`"}} javascript/higher_funcs -.-> lab-28290{{"`Every NTH Element`"}} end

Function to Return Every NTH Element of an Array

To return every nth element in an array, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use the Array.prototype.filter() method to create a new array that contains every nth element of a given array.
  3. Use the following function to implement the above step:
const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);
  1. To test the function, use the following code:
everyNth([1, 2, 3, 4, 5, 6], 2); // [ 2, 4, 6 ]

This will return a new array with every second element of the input array.

Summary

Congratulations! You have completed the Every NTH Element lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like