<tutorialjinni.com/>

JavaScript Cut Array in Half

Posted Under: JavaScript, Programming, Snippets, Tutorials on Jun 15, 2019
This tutorial explain how to cut a JavaScript array in half no matter what the size is. it will splice the array in equal halves.
    var myArray = [1,2,3,4,5,6,7,8,9];
    var halfLength = Math.ceil(myArray.length / 2); 
    var firstHalf =  myArray.splice(0,halfLength);
    console.log(firstHalf);
    console.log(myArray); // SECOND HLAF

Output

[1, 2, 3, 4, 5]
[6, 7, 8, 9]
If the number of elements in an array are even, array will be divided equally. However, if the number of elements in an array are odd, and Math.ceil is taken then first half of the array will get an extra element. If Math.floor is taken then the second half will have that extra element.
© Tutorial Jinni