Last updated: Mar 4, 2024
Reading timeยท3 min
To get every Nth element of an array:
for
loop to iterate the array every N elements.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.
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.
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.
Array.filter()
This is a two-step process:
Array.filter()
method to iterate over the array.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.
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.
You can learn more about the related topics by checking out the following tutorials: