1 line of code: How to get every n-th item of an Array
Tags: javascript, webdev, productivity, codequality
Published: 2021-11-23 15:53:31

```javascript
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](https://perf.link/#eyJpZCI6InptazdubW1rMmU1IiwidGl0bGUiOiJnZXQgZXZlcnkgbi10aCBpdGVtIG9mIGFuIEFycmF5ICIsImJlZm9yZSI6ImNvbnN0IGRhdGEgPSBbLi4uQXJyYXkoMTAwMCkua2V5cygpXVxuY29uc3QgbnRoSXRlbXMgPSAoYXJyLCBwb3MpID0%2BIGFyci5maWx0ZXIoKGFyciwgaW5kZXgpID0%2BIGluZGV4ICUgcG9zID09PSBwb3MgLSAxKVxuY29uc3QgbnRoSXRlbXMyID0gKGFyciwgcG9zKSA9PiBBcnJheS5mcm9tKHtsZW5ndGg6fn4oYXJyLmxlbmd0aC9wb3MpfSwgKF8saSk9PmFyclsoaSsxKSpwb3MtMV0pIiwidGVzdHMiOlt7Im5hbWUiOiJUZXN0IDEiLCJjb2RlIjoibnRoSXRlbXMoZGF0YSkiLCJydW5zIjpbMjAwMCw1MDAsMjAwMCw2MDAwLDI1MDAsNTAwMCwzNTAwLDMwMDAsMzAwMCw0MDAwLDUwMDAsNTAwMCw0NTAwLDU1MDAsMzAwMCwxMDAwLDMwMDAsMzAwMCwyMDAwLDM1MDAsMjAwMCw1MDAsNDAwMCwxNTAwLDM1MDAsMzUwMCwxNTAwLDEwMDAsNDAwMCwyNTAwLDUwMDAsMjUwMCwzNTAwLDQ1MDAsNTUwMCwzMDAwLDg1MDAsNDUwMCw3MDAwLDU1MDAsNTUwMCw3MDAwLDQwMDAsNDAwMCwzNTAwLDU1MDAsMzUwMCw2NTAwLDU1MDAsNTUwMCw2MDAwLDM1MDAsNDUwMCw1MDAwLDMwMDAsNDUwMCwzMDAwLDU1MDAsNzUwMCw1MDAwLDU1MDAsNDAwMCw4MDAwLDUwMDAsNzAwMCw0NTA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MwMDAsMzEyNTAwLDUxNTAwMCwxNjcxMDAwLDgwNjUwMCw3MDA1MDAsMzEyNTAwLDEyMzg1MDAsNzk2MDAwLDgxNTAwMCwzNzUwMDAsMzEzMDAwLDkyNDAwMCwzNzUwMDAsNTAwNTAwLDU0MjAwMCwzNzUwMDAsMTE0NDUwMCw5MTYwMDAsODk2MDAwLDY4NDUwMCwxMzUwMDAwLDU1NDAwMCw0MTUwMDAsNzQ2MDAwXSwib3BzIjo2MDc4MzV9XSwidXBkYXRlZCI6IjIwMjEtMTEtMjRUMDg6MTU6MDIuNjY3WiJ9))**

```javascript
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](https://github.com/martinkr/onelinecode)
The library is also published to [npm as @onelinecode](https://www.npmjs.com/package/@onelinecode/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](http://twitter.com/_martinkr) and consider to [buy me a coffee](https://www.buymeacoffee.com/martinkr)

Photo by [zoo_monkey](https://unsplash.com/@zoo_monkey) on [Unsplash](https://unsplash.com/s/photos/fuji)

---