DEV Community

Cover image for 1 line of code: How to get every n-th item of an Array
Martin Krause
Martin Krause

Posted on

1 line of code: How to get every n-th item of an Array

const nthItems = (arr, pos) => arr.filter((arr, index) => index % pos === pos - 1);
Enter fullscreen mode Exit fullscreen mode

Returns all items which are at the n-th-position.


Optimised code (Benchmark)

const nthItems = Array.from({ length: ~~(arr.length / pos) }, (_, i) => arr[(i + 1) * pos - 1])
Enter fullscreen mode Exit fullscreen mode

The repository & npm package

You can find the all the utility functions from this series at github.com/martinkr/onelinecode
The library is also published to npm as @onelinecode for your convenience.

The code and the npm package will be updated every time I publish a new article.


Follow me on Twitter: @martinkr and consider to buy me a coffee

Photo by zoo_monkey on Unsplash


Top comments (2)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

This method is hundreds of times faster...

const nthItems = (arr, pos) => Array.from({length:~~(arr.length/pos)}, (_,i)=>arr[(i+1)*pos-1])
Enter fullscreen mode Exit fullscreen mode
Collapse
 
martinkr profile image
Martin Krause

Amazing, thank you.

I updated the article and the code.

Cheers!