Split an array into half in JavaScript
Do you want to split an array into half in JavaScript, divide exactly into equal part?
You can use the Array.prototype.splice()
method
Advertisements
const list = [1, 2, 3, 4, 5, 6] const half = Math.ceil(list.length / 2); const firstHalf = list.splice(0, half); // [1,2,3] const secondHalf = list.splice(-half); // [4,5,6]
When the length of the array is in even number, the result will be like the above.
If the length is odd one, like below:
const list = [1, 2, 3, 4, 5] const half = Math.ceil(list.length / 2); const firstHalf = list.splice(0, half); const secondHalf = list.splice(-half);
Advertisements
Then the result will be,
[1,2,3] [4,5]
Happy Learning 🙂