I have an array I would like to split in half. So I can position the first half on the right side and the second half on the left side.
I have used the splice function before:
var leftSide = arrayName.splice(0,2);
But not sure how to splice it in half no matter the size, because the array will change in size dynamically.
Using the copyOfRange() method you can copy an array within a range. This method accepts three parameters, an array that you want to copy, start and end indexes of the range. You split an array using this method by copying the array ranging from 0 to length/2 to one array and length/2 to length to other.
It's not working because you are removing items from the array while looping through the keys. When you remove an item, it will rearrange the other items depending on how the array is implemented internally, and you end up with a loop that doesn't iterate over the keys that you expect.
splice alters the length of an array.
splice & delete Array item by index The slice( ) method copies a given part of an array and returns that copied part as a new array. It doesn't change the original array. The splice( ) method changes an array, by adding or removing elements from it. Note: the Slice( ) method can also be used for strings.
var half_length = Math.ceil(arrayName.length / 2); var leftSide = arrayName.splice(0,half_length);
edited the code following @Lightness Races in Orbit comment
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.
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.
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.
You can get around this by using slice
instead of splice
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With