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.
Function to Return Every NTH Element of an Array
To return every nth element in an array, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use the
Array.prototype.filter()method to create a new array that contains everynthelement of a given array. - Use the following function to implement the above step:
const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 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.