const oddItems = arr => arr.filter((_, i) => i & 1 === 1);
Returns an array which contains every odd (second) item of the original array.
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 (13)
Not looked for faster methods yet, but the current one seems overly verbose. Also, what is
Binary filters are even faster than the modulo:
Faster still if you omit the unnecesary
=== 1- it's about even on Firefox, but consistently quicker on Chrome (10-15%) - link
Much faster again (on all tested browsers):
Hi Jon Randy,
I updated the benchmark on hasty - impressive improvement!
I updated the code and the article.
Thank you for the improved code.
If you are already using a for loop, you can also jump 2 steps on every iteration:
Haha... yeah - oops
You might want to make the benchmark call the functions as well as define them! :P
wouldn't jumping 2 steps ensure only odd positional, but not values?
(I just assume an unsorted array of random values)
Odd positional is what we're after
I checked the performance on hasty and indeed much faster. I updated the code and the article.
Thank you for your contribution. The "which" is a copy paste error :D
If you have any performance improvements, please share them and I'll happily adjust the code and the article.
Some comments have been hidden by the post's author - find out more