Get every Nth Element of Array using JavaScript

avatar

Borislav Hadzhiev

Thu Nov 04 20212 min read

banner

Photo by Grant Ritchie

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.
index.js
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 for loop is efficient here, because we don't have to loop over every element in the array and skip the ones we don't need.

By incrementing the index with the Nth number, we are able to skip the irrelevant array elements.

Some solutions on the internet use the filter() method. But the filtermethod 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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee