const nthItems = (arr, pos) => arr.filter((arr, index) => index % pos === pos - 1);
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])
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)
This method is hundreds of times faster...
Amazing, thank you.
I updated the article and the code.
Cheers!