Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split an array into two based on a index in javascript

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.

like image 415
user811433 Avatar asked Jul 29 '11 11:07

user811433


People also ask

How do you split an array at a specific index?

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.

Can you split an array in JavaScript?

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.

How do you split an array into array pairs in JavaScript?

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 .


2 Answers

Use slice, as such:

var ar = [1,2,3,4,5,6];  var p1 = ar.slice(0,4); var p2 = ar.slice(4); 
like image 192
TJHeuvel Avatar answered Oct 10 '22 00:10

TJHeuvel


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"] 
like image 39
Mark Amery Avatar answered Oct 10 '22 00:10

Mark Amery