const splitInHalf = arr => [arr.slice(0, Math.ceil(arr.length / 2)), arr.slice(Math.ceil(arr.length / 2))];
Returns an new array where the first entry is the "first" and the second entry is the "second" half 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 (17)
Probably slower, but:
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
Here's an array one:
Checked the benchmark (jsbench.github.io/#44d4426b04ed292...) and yours is way faster.
I updated the code and the article!
Thank you
Careful with this one though - mutation
Good spot. Definitely avoid this method unless you love bugs and impure functions 😅
Non-mutating version - slower though:
Speed comparision of all 3 methods.
I will stick with the original version.
If you find a faster one without mutations we can use it.
Cheers!
Ah, I misread - thought you were doing strings
No Problem, strings will be next month ;)
Cheers!
I don't see any use case
You have view with dynamic columns. You want to display all the data within the array evenly between these columns. As columns are added/removed you need to split the array.
In my opinion, the alignment of columns is done in CSS.
Yes, you can definitely use css columns, but sometimes you just need things or flexible. Maybe it's not a column, but a grid. Or maybe you start with columns, but can divide them into grids (like in VSCode).
Another use case could be splitting up players into teams. If you have a group of players and you need to make equal teams, then you'll need to split that array.
far fetched...but OK, enough words for such an simple function....
You said you didn't see any use cases, I'm merely presenting them to you. Do what you will with it.