I have an array with a list of objects. I want to split this array at one particular index, say 4 (this in real is a variable). I want to store the second part of the split array into another array. Might be simple, but I am unable to think of a nice way to do this.
To split a string at a specific index, use the slice method to get the two parts of the string, e.g. str. slice(0, index) returns the part of the string up to, but not including the provided index, and str. slice(index) returns the remainder of the string.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
To do this, we call reduce with a callback that returns the result array that's created from the result array spread into a new array and an array with the next 2 items in the list if index is event. We get the next 2 items with the slice with index and index + 2 as the indexes. Otherwise, we just return result .
Use slice, as such:
var ar = [1,2,3,4,5,6]; var p1 = ar.slice(0,4); var p2 = ar.slice(4);
You can use Array@splice
to chop all elements after a specified index off the end of the array and return them:
x = ["a", "b", "c", "d", "e", "f", "g"]; y = x.splice(3); console.log(x); // ["a", "b", "c"] console.log(y); // ["d", "e", "f", "g"]
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