Clue Mediator

Divide an array in half using JavaScript

📅May 23, 2022

In this article, you will learn how to divide an array in half using JavaScript. There are multiple ways to split an array into half but here we will show you the best and short method to half an array.

Checkout more articles on JavaScript

Let’s split an array into two parts using slice() and Math function method.

const list = [1, 2, 3, 4, 5, 6, 7];
const half = Math.ceil(list.length / 2);

const firstHalf = list.slice(0, half);
// Output: [1, 2, 3, 4]

const secondHalf = list.slice(-half + (list.length % 2));
// Output: [5, 6, 7]

If there are an even number of items in the list, the result is divided in half.

If the number is even, for example

const list = [1, 2, 3, 4, 5, 6, 7, 8];

The result will be

[1, 2, 3, 4]
[5, 6, 7, 8]

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂