Get Every Nth Element Of Array In JavaScript

To get every nth element of array in JavaScript –

  1. Declare an empty array to store the results.
  2. Use a for loop to iterate over every nth element of the original array.
  3. Add each element to the new array.
  4. Return the new array.

Let’s discuss this approach in detail below.

get every nth element of an array in javascript

Get Every Nth Element Of Array In JavaScript

Consider the following array:

var arr = ['a', 'b', 'c', 'd', 'e', 'f'];

We want to get every 2nd element of this array, starting from index 0. We can do that using a for loop as follows:

var arr = ['a', 'b', 'c', 'd', 'e', 'f'];

var result = []; //an empty array to store results

for(var i=0; i < arr.length; i+=2){ //iterate over every 2nd element

 result.push(arr[i]); // push the element into the result array

}

console.log(result); // logs ['a', 'c', 'e']

As you can see, we declared an empty array to store results. We then iterated over every 2nd element of the input array and added it to the result array. Finally, we logged the result to the console.

Let’s write a reusable function that takes two arguments – an array and a number – and returns every nth element of the array.

function getEveryNthElement(arr, n){

var result = []; //an empty array to store results

for(var i=0; i < arr.length; i+=n){ //iterate over every nth element

  result.push(arr[i]); // push the element into the result array

}

return result;

}

var arr = ['a', 'b', 'c', 'd', 'e', 'f'];

console.log(getEveryNthElement(arr, 2)); // logs ['a', 'c', 'e']

As you can see, we declared a function that takes two arguments – an array and a number. The function returns every nth element of the array. We then invoked the function with an array and the number 2 as arguments and logged the result to the console.

You can try this function with different values of n to get a better understanding.

We hope this article was helpful in explaining how to get every nth element of an array in JavaScript. If you have any questions or suggestions, please feel free to leave a comment.

Leave a Reply