How to divide an array in half in JavaScript
By Flavio Copes
Learn how to divide an array in half in JavaScript using slice() together with Math.ceil() on the length, so odd-length arrays split down the middle.
~~~
How can you divide an array in 2 parts, divided exactly in the middle?
Use the Array instance slice() method:
const list = [1, 2, 3, 4, 5, 6]
const half = Math.ceil(list.length / 2);
const firstHalf = list.slice(0, half)
const secondHalf = list.slice(half)
If the list contains an even number of items, the result is split with exactly half the items.
If the number is odd, for example
[1, 2, 3, 4, 5]
The result will be
[ 1, 2, 3 ]
[ 4, 5 ] ~~~
Related posts about js: