DEV Community

Cover image for 1 line of code: How to split an Array in half
Martin Krause
Martin Krause

Posted on • Updated on

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

const splitInHalf = arr => [arr.slice(0, Math.ceil(arr.length / 2)), arr.slice(Math.ceil(arr.length / 2))];
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Probably slower, but:

const splitInHalf = s=>s.match(new RegExp('.{1,'+~~((s.length+1)/2)+ '}','g'))
Enter fullscreen mode Exit fullscreen mode
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 🎖️ • 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!

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
 
frankwisniewski profile image
Frank Wisniewski

I don't see any use case

Collapse
 
jamesthomson profile image
James Thomson

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.

Collapse
 
frankwisniewski profile image
Frank Wisniewski • Edited

In my opinion, the alignment of columns is done in CSS.

<!DOCTYPE html>
<html lang="de">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    .myList{
     column-count: 2; 
     column-width: 50%;
     column-rule-style:dotted; 
     column-rule-width:1px; 
    }
    .myList p{
      display:inline-block;
      width:100%;
    }
  </style>
</head>
<body>
<div class="myList" id=myContainer></div>
<script>
    let myArray=[1,1,5,3,4,5,6,7,8,1,12,13,15,16]
    let myHTML = ''
    myArray.map(el => myHTML += '<p>'+el+'</p>')
    myContainer.innerHTML=myHTML         
</script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
jamesthomson profile image
James Thomson

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.

Thread Thread
 
frankwisniewski profile image
Frank Wisniewski

far fetched...but OK, enough words for such an simple function....

Thread Thread
 
jamesthomson profile image
James Thomson

You said you didn't see any use cases, I'm merely presenting them to you. Do what you will with it.

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️ • Edited
const split = num => ([...arr]) => Array(num).fill(0)
   .map((_,i)=>Math.floor(arr.length/num)+(i<arr.length%num))
   .map(n => arr.splice(0, n))
Enter fullscreen mode Exit fullscreen mode