DEV Community

Discussion on: 1 line of code: How to split an Array in half

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

Here's an array one:

const splitInHalf = a=>[a,a.splice(~~((a.length+1)/2))]
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
martinkr profile image
Martin Krause

Checked the benchmark (jsbench.github.io/#44d4426b04ed292...) and yours is way faster.
I updated the code and the article!
Thank you

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

Careful with this one though - mutation

Thread Thread
 
jackmellis profile image
Jack

Good spot. Definitely avoid this method unless you love bugs and impure functions πŸ˜…

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

Non-mutating version - slower though:

const splitInHalf = (a,b=[])=>[b=[...a],b.splice(b.length+1>>1)]
Enter fullscreen mode Exit fullscreen mode

Speed comparision of all 3 methods.

Thread Thread
 
martinkr profile image
Martin Krause

I will stick with the original version.
If you find a faster one without mutations we can use it.
Cheers!