Splice an array in half, no matter the size?
var half_length = Math.ceil(arrayName.length / 2);
var leftSide = arrayName.splice(0,half_length);
edited the code following @Lightness Races in Orbit comment
Avoid Mutations
If you need to avoid mutations, for example if you have to split an array in react you don't want to mutate the original or it could lead to some very strange behaviour in your app.
What is a Mutation?
A mutation is when you change a non primitive, like an object or array. Using an array method like splice will cause the original array to be manipulated. You can always tell if a method will mutate by whether or not it returns a new array or object.
Why can Mutations be "bad"?
When you mutate an object or array you change that original reference. This means that if you use the original reference you will get the new value. This is best shown with an example.
const myObj = { key: "some value" };
const newObj = myObj;
newObj.key = "some other value";
console.log(myObj) // will log { key: "some other value" };
As you can see the object myObj
had the value of key changed as well. Scary stuff.
Use Slice
You can get around this by using slice
instead of splice
Example
let yourArray = props.someArray;
let halfwayThrough = Math.floor(yourArray.length / 2)
// or instead of floor you can use ceil depending on what side gets the extra data
let arrayFirstHalf = yourArray.slice(0, halfwayThrough);
let arraySecondHalf = yourArray.slice(halfwayThrough, yourArray.length);
You can simply refer to the array's length:
var leftSide = arrayName.splice(0, Math.floor(arrayName.length / 2));
Since .splice()
actually removes elements from the source array, the remaining elements in the array will be the elements for the right half.
Math.floor()
will round down to give the left side one less than the right side for odd lengths. You could use Math.ceil()
if you want to round up to give the left side one more than the right side when the length is odd.
Take a look at lodash chunk
:
var myArray = [1, 2, 3, 4, 5, 6, 7, 8];
var pivot = _.ceil(myArray.length / 2);
// => 4
console.log(_.chunk(myArray, pivot));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>