In this tutorial, I will show you how to divide a JavaScript array into two equal parts (or almost equal if the array has an odd length).
Use the Array instance slice()
method:
const test_array = ["a", "b", "c", "d", "e", "f"]; 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:
>>> firstHalf ["a", "b", "c"] >>> secondHalf ["d", "e", "f"]
The Math.ceil()
function always rounds a number up to the next largest integer. We add this in case the array length is odd and list.length / 2
is not a whole number.
If the array contains an odd number of elements, the result is split as close to half as possible.
const odd_array = [1, 2, 3, 4, 5] const half = Math.ceil(list.length / 2); const firstHalf = list.slice(0, half) const secondHalf = list.slice(-half)
Since there are 5 elements, the half variable will be Math.ceil(5 / 2) = 3
. So, the array will split on the third element.
>>> firstHalf [1, 2, 3] >>> secondHalf [4, 5]