w3resource

JavaScript: Get every nth element in a given array

JavaScript fundamental (ES6 Syntax): Exercise-21 with Solution

Write a JavaScript program to get every nth element in a given array.

  • Use Array.prototype.filter() to create a new array that contains every nth element of a given array.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
// Define a function called `every_nth` that filters an array and returns every nth element.
const every_nth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);

// Example usage
console.log(every_nth([1, 2, 3, 4, 5, 6], 1)); // [1, 2, 3, 4, 5, 6]
console.log(every_nth([1, 2, 3, 4, 5, 6], 2)); // [2, 4, 6]
console.log(every_nth([1, 2, 3, 4, 5, 6], 3)); // [3, 6]
console.log(every_nth([1, 2, 3, 4, 5, 6], 4)); // [4]

Output:

[1,2,3,4,5,6]
[2,4,6]
[3,6]
[4]

Visual Presentation:

JavaScript Fundamental: Get every n<sup>th</sup> element in a given array
JavaScript Fundamental: Get every n<sup>th</sup> element in a given array

Flowchart:

flowchart: Get every nth element in a given array

Live Demo:

See the Pen javascript-basic-exercise-1-21 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to extend a 3-digit color code to a 6-digit color code.
Next: Write a JavaScript program to filter out the non-unique values in an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-21.php