In this post, we will learn how to divide an array into half using JavaScript.
We can divide/split an array in half using the Array.splice()
method. With this method, we can divide the array exactly in the middle and create two separate arrays containing the elements.
The Array.splice()
method is used to add or remove elements from an array. This method does not modify the original array upon which it is called.
Syntax:
const nums = ["One", "Two", "Three", "Four"];
nums.slice(0,3) // [ 'One', 'Two', 'Three' ]
So let’s use this method to create two new arrays from a single array containing the divided elements.
Suppose we have an array with 4 elements and to divide it equally we need to have two elements in each newly created array.
So in JavaScript, we can do it like this.
const arr = [1, 2, 3, 4];
const firstArr = arr.slice(0,2)
const secondArr = arr.slice(2)
console.log(firstArr) // [ 1, 2 ]
console.log(secondArr) // [ 3, 4 ]
Now, this is easy because we know how many elements were there in the array.
So what if we don’t know about the number of items present in the array ??
To deal with this issue, we have to code a function that can take the array, check the number of items in it and then divide the array accordingly.
So let’s see how we can do it with the help of JavaScript below.
const arr = [1, 2, 3, 4];
function divideArray(arr){
const middle = Math.ceil(arr.length/2)
const firstHalf = arr.slice(0, middle)
const secondHalf = arr.slice(middle)
return { firstHalf , secondHalf }
}
const myArr = divideArray(arr)
console.log(myArr.firstHalf) // [ 1, 2 ]
console.log(myArr.secondHalf) // [ 3, 4 ]
Code Explanation:
In the above code, we have a function divideArray()
that takes an array as an argument and returns us the two arrays containing the divided elements of the given array.
To find at which place we have to divide the array equally we used Math.ceil(arr.length/2)
. The arr.length
gets the number of elements in the given array. And we have divided it by 2 to get the middle value of the array.
Since the array length could be odd or even, we have to use the Math.ceil()
method.
The Math.ceil()
method rounds off a number up to the next largest integer number. For Example:
5/2 // 2.5
Math.ceil(5/2) // 3
So if we pass an array with an odd number of items in it, we will get
const myArr = divideArray([1, 2, 3, 4, 5])
console.log(myArr.firstHalf) // [ 1, 2, 3 ]
console.log(myArr.secondHalf) // [ 4, 5 ]
So, this is how we can split a given array into half (two different arrays) without modifying the original array.