DEV Community

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

Collapse
 
martinkr profile image
Martin Krause

Thank you for your contribution. I was going test the performance and compare both code snippets but upon closer inspection I think yours is only working on strings not array. Can you take a closer look?

Thank you

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Ah, I misread - thought you were doing strings

Thread Thread
 
martinkr profile image
Martin Krause

No Problem, strings will be next month ;)
Cheers!

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!