The best way to split an array into two halves in JavaScript is by using the Array.prototype.slice()
method, because it returns a portion of the array without modifying the original array (i.e. in an immutable / non-destructive way). For example:
const arr = [1, 2, 3, 4, 5, 6, 7]; const middle = Math.floor(arr.length / 2); const left = arr.slice(0, middle); const right = arr.slice(middle); console.log(left); // output: [1, 2, 3] console.log(right); // output: [4, 5, 6, 7] console.log(arr); // output: [1, 2, 3, 4, 5, 6, 7]
Please note that if you omit the second argument to the slice()
method (such as in the "right
" array in the code above), it extracts all elements of the array starting from the specified index till the end of the array (i.e. arr.length
).
As you can see in the example code above, an array with odd number of elements would yield unbalanced left / right arrays. Using Math.floor()
would make the left array have less elements than the right array. If for some reason you would rather have more elements in the left array than the right one, then you can simply substitute Math.floor()
with Math.ceil()
like so:
const arr = [1, 2, 3, 4, 5, 6, 7]; const middle = Math.ceil(arr.length / 2); const left = arr.slice(0, middle); const right = arr.slice(middle); console.log(left); // output: [1, 2, 3, 4] console.log(right); // output: [5, 6, 7]
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.