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.
To divide an array in 2 parts, exactly in the middle, calculate the midpoint with Math.ceil() and use the Array instance slice() method twice:
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)
firstHalf //[1, 2, 3]
secondHalf //[4, 5, 6]
slice() takes a start index and an end index, and returns a new array with the items between them. The end index is not included, which is why slice(0, 3) and slice(3) line up perfectly with no overlap and no gap.
When you call slice() with a single argument, it extracts from that index to the end of the array.
What happens with an odd number of items?
If the list contains an even number of items, the result is split with exactly half the items in each part.
If the number is odd, one half has to get the extra item. Math.ceil() rounds up, so the extra item goes to the first half:
const grades = [1, 2, 3, 4, 5]
const half = Math.ceil(grades.length / 2)
grades.slice(0, half) //[1, 2, 3]
grades.slice(half) //[4, 5]
If you’d rather have the extra item in the second half, use Math.floor() instead. With the same 5-item array you’d get [1, 2] and [3, 4, 5].
Does this change the original array?
No. slice() does not touch the array it’s called on. After the code above, list still contains all 6 items. You get two new arrays.
Be careful not to confuse slice() with splice(). The names are one letter apart but splice() mutates the array:
const list = [1, 2, 3, 4, 5, 6]
const firstHalf = list.splice(0, 3)
firstHalf //[1, 2, 3]
list //[4, 5, 6]
Here splice() removed the first 3 items from list and returned them. That can be exactly what you want, for example when you’re consuming a queue in batches. But if you used it by accident, the fix is to switch back to slice(), which leaves the original array intact.
Related posts about js: