Javascript – how to split array in half

half circle in front of a code

Very briefly we will learn how to split array in half

I will show you how to do it with splice method to avoid mutation but we will also do it with mutation.

But first…

What is Mutation?

Mutation occurs when you try to change non primitive value (like in our case array) that will change original value and not create a new one.

Essentialy when it comes to non primitive values javascript is just pointing to said value
example:

const array1 = ["What", "Up"]

const array2 = array1

Even tho we have 2 variables they are the same!
So when you change one the other one will have the same value because… well they’re the same.

1. how to split array in half without Mutating Original Array

Let’s start by creating a function

function arraySplit(array) {

}

Next step is to find a half way point

function arraySplit(array) {
  const halfwayPoint = Math.floor(array.length / 2)
  
}

Now we will find first and second half using slice as slice method will not mutate original array but instead create a new one

function arraySplit(array) {
  const halfwayPoint = Math.floor(array.length / 2)
  
  const firstHalf = array.slice(0, halfwayPoint)
  const arraySecondHalf = array.slice(halfwayPoint, array.length)
}

and lastly we will just return the two halfs in any way you need. I will return an array with two halfed arrays inside

function arraySplit(array) {
  const halfwayPoint = Math.floor(array.length / 2)
  
  const firstHalf = array.slice(0, halfwayPoint)
  const arraySecondHalf = array.slice(halfwayPoint, array.length)
  
  return [firstHalf, arraySecondHalf]
}

and there you go, that’s how you split an array in Javascript without mutating the original array

2. With Mutating Original Array

If you don’t care or plan to use original array.

We will start the same way by creating an function and finding an halfway point

function arraySplit(array) {
  const halfwayPoint = Math.floor(array.length / 2)
  
}

next we will use splice to cut array in half and save to a variable

function arraySplit(array) {
  const halfwayPoint = Math.floor(array.length / 2)
  
  const leftSide = array.splice(0, halfwayPoint);
}

lastly we will return new Array with tho arrays inside them:

  • Leftside
  • original array, that is now modified and now only contains second half of it’s original values

So be aware that you are mutating your original array here!

function arraySplit(array) {
  const halfwayPoint = Math.floor(array.length / 2)
  
  const leftSide = array.splice(0, halfwayPoint);
  
  return [leftSide, array];
}

And here you go!
Two ways to split array in half in JS. One with mutating and one without.

awesome work image

Leave a Comment

Your email address will not be published. Required fields are marked *