How to Divide an Array in Half in JavaScript
Table of Contents
Arrays are ubiquitous in JavaScript because of their ability to hold several items in a single array.
Depending on the circumstances, sometimes you want to divide an array into two halves, usually to perform some kind of operation to each half.
In this post, we'll learn the best way to divide an array into two halves in JavaScript.
How to divide an array into two halves
Before we divide an array in half, let's start with our example array:
JAVASCRIPTconst array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(array);
BASH(10) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
To divide it in half, we first need to get the length of the array and then divide it by two. Also, we'll use a ceiling function to round up the result of the division.
That will let us know the midpoint of the array.
JAVASCRIPTconst array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const midpoint = Math.ceil(array.length / 2);
console.log(midpoint);
BASH5
Using this midpoint, we can now get two sections of the array using the slice()
function.
JAVASCRIPTconst array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const midpoint = Math.ceil(array.length / 2);
const firstHalf = array.slice(0, midpoint);
const secondHalf = array.slice(-midpoint);
console.log(firstHalf);
console.log(secondHalf);
BASH(5) [1, 2, 3, 4, 5]
(5) [6, 7, 8, 9, 10]
Conclusion
In this post, we learned how to divide an array into two halves in JavaScript.
Simply calculate the midpoint of the array and use the slice()
function to get two halves of the array.
Thanks for reading and happy coding!
- Getting Started with TypeScript
- Getting Started with Express
- Git Tutorial: Learn how to use Version Control
- How to Set Up Cron Jobs in Linux
- How to deploy a .NET app using Docker
- How to build a Discord bot using TypeScript
- How to deploy a PHP app using Docker
- Getting Started with Sass
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Getting User Location using JavaScript's Geolocation API
- Creating a Twitter bot with Node.js