# Get every Nth Element of Array using JavaScript

Last updated: Mar 4, 2024
3 min

## #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
```Copied!```function getEveryNth(arr, nth) {
const result = [];

for (let index = 0; index < arr.length; index += nth) {
result.push(arr[index]);
}

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));
``````

The function takes an array and `n` as parameters and returns a new array that contains every Nth element of the original array.

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

We used a basic `for` loop to iterate over the array every N elements.

On each iteration, we 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 by `n`, we are able to skip the irrelevant array elements.

index.js
```Copied!```function getEveryNth(arr, nth) {
const result = [];

for (let i = 0; i < arr.length; i += nth) {
result.push(arr[i]);
}

return result;
}
``````

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

Alternatively, you can use the `filter()` method.

## #Get every Nth Element of Array using `Array.filter()`

This is a two-step process:

1. Use the `Array.filter()` method to iterate over the array.
2. Use the current index to check if each element should be added to the new array.
index.js
```Copied!```function getEveryNth(arr, nth) {
return arr.filter((_element, index) => {
return index % nth === 0;
});
}

// ๐๏ธ [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));
``````

The function we passed to the Array.filter() method gets called with each element in the array.

On each iteration, we use the modulo `%` operator to check if the remainder of dividing the current index by `n` is `0`.

The modulo operator returns the remainder of dividing the first number by the second.

index.js
```Copied!```console.log(4 % 2); // ๐๏ธ 0
console.log(5 % 2); // ๐๏ธ 1
``````

The `filter()` method returns a new array that only contains the elements that meet the condition.

However, the `filter` method invokes a function for every element in the array, which is very inefficient in this scenario.

Ideally, you would want to only iterate over the array every N elements.

The `for` loop is more efficient because it doesn't have to loop through the entire array.