
Where indexes use whole numbers this would be an issue so we need to then either round up or down to get a whole number. If the length was an odd number, for example 5, when we divide it in half we will end up with a decimal or a float of 2.5. We are using Math.ceil here in case we have an odd length of our array, in the example above we have 4 items so the length is even which gives us a whole number or an integer when we divide the length in half. You might be wondering what the Math.ceil is for. We do this by first finding the index that is half way through the array, once we have that index we know that we need to get all items up to that point and save that into a new array, and then do the same for all items after that index as well for the second half. log (secondHalfOfArray ) // Īs you can see, we have now split an array into two in JavaScript (split in half) with the method. slice ( 0, halfWayIndex ) const secondHalfOfArray = myArray. length / 2 ) const firstHalfOfArray = myArray. Convert all elements with the ocean class into the array.Const myArray = const halfWayIndex = Math. When both arguments are passed, the slice method returns a new array starting at the index of the first argument and it ends on the second argument -1 (minus one) of the initial array. To pull off the front of an array, we need to pass two arguments to the Array.slice() method. The first target indexes of an initial array You need to call it with no arguments and save the result to a new variable.Įxample const isWatched = Ĭonst myFriendWatched = isWatched. This is often used to create a copy of an array for further transformations that do not need to change the original array. You can call slice with no arguments at all: arr.slice () creates a copy of the initial array. Let's explore the use of the Array.slice() method. This is similar to the str.slice() string method but returns subarrays instead of substrings.

In this case, the count will be carried out from the end of the array. Note that both indices for start and end could be negative. It returns a new array into which it copies the elements from index start to end (not including end). And note that the original array is not modified.

According to the MDN Web Docs documentation, the Array.slice() method, in particular, sends back a shallow copy of a certain part of an array to a brand new array object, that is selected from beginning to end (not including an end).
