DEV Community

Cover image for 1 line of code: How to get every odd item of an Array

1 line of code: How to get every odd item of an Array

Martin Krause on November 09, 2021

const oddItems = arr => arr.filter((_, i) => i & 1 === 1); Enter fullscreen mode Exit fullscreen mode Ret...
Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

Not looked for faster methods yet, but the current one seems overly verbose. Also, what is which for?

const oddItems = arr => arr.filter((_, index) => index % 2)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
lexlohr profile image
Alex Lohr

Binary filters are even faster than the modulo:

const oddItems = arr => arr.filter((_, i) => i & 1 === 1);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

Faster still if you omit the unnecesary === 1 - it's about even on Firefox, but consistently quicker on Chrome (10-15%) - link

const oddItems = arr => arr.filter((_, i) => i & 1)
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

Much faster again (on all tested browsers):

const oddItems = (arr, odds=[], i=0)=>{ for (i=0;i<arr.length;i++) (i & 1) && odds.push(arr[i]); return odds}
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
martinkr profile image
Martin Krause

Hi Jon Randy,

I updated the benchmark on hasty - impressive improvement!
I updated the code and the article.

Thank you for the improved code.

Cheers!

Thank you!

Thread Thread
 
lexlohr profile image
Alex Lohr

If you are already using a for loop, you can also jump 2 steps on every iteration:

const oddItems = (arr, odds=[], i) => { for (i = 1; i < arr.length; i = i + 2) odds.push(arr[i]); return odds}
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

Haha... yeah - oops

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

You might want to make the benchmark call the functions as well as define them! :P

Thread Thread
 
giulio profile image
Giulio "Joshi"

wouldn't jumping 2 steps ensure only odd positional, but not values?
(I just assume an unsorted array of random values)

Thread Thread
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

Odd positional is what we're after

Collapse
 
martinkr profile image
Martin Krause

Hi Alex,

I checked the performance on hasty and indeed much faster. I updated the code and the article.

Thank you!

Collapse
 
martinkr profile image
Martin Krause

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.

Cheers,

Martin

Some comments have been hidden by the post's author - find out more