Get every Nth Element of Array using JavaScript


Borislav Hadzhiev

Last updated: Sep 7, 2022


Photo from Unsplash

Get every Nth Element of Array in JavaScript #

To get every Nth element of an array:

  1. Declare an empty array variable.
  2. Use a for loop to iterate the array every N elements.
  3. On each iteration, push the element to the new array.
  4. The final array will contain every Nth element of the original array.
function getEveryNth(arr, nth) { const result = []; for (let i = 0; i < arr.length; i += nth) { result.push(arr[i]); } return result; } // 👇️ [1, 3, 5] console.log(getEveryNth([1, 2, 3, 4, 5, 6], 2)); // 👇️ [2, 8, 14] console.log(getEveryNth([2, 4, 6, 8, 10, 12, 14], 3));

We created a reusable function that gets every Nth element of an array.

The first step is to declare an empty array variable that will store the results.

We use a basic for loop to iterate over the array every N elements and push the element to the results array.

Using a for loop is efficient here because we don't have to loop over every element in the array and can skip the ones we don't need.

By incrementing the index with the specified N, we are able to skip the irrelevant array elements.

Some solutions on the internet use the filter() method. But the filter method invokes a function for every element in the array, which is very inefficient in this scenario.

Once the for loop has finished iterating, the results array contains every Nth element of the original array.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.