split an array into two based on a index in javascript

JavascriptArraysSplit

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

Use slice, as such:

var ar = [1,2,3,4,5,6];

var p1 = ar.slice(0,4);
var p2 = ar.slice(4);

Solution 2 - Javascript

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"]

Solution 3 - Javascript

use slice:

var bigOne = [0,1,2,3,4,5,6];
var splittedOne = bigOne.slice(3 /*your Index*/);

Solution 4 - Javascript

I would recommend to use slice() like below

ar.slice(startIndex,length); or ar.slice(startIndex);

var ar = ["a","b","c","d","e","f","g"];

var p1 = ar.slice(0,3);
var p2 = ar.slice(3);

console.log(p1);
console.log(p2);

Solution 5 - Javascript

Simple one function from lodash:

const mainArr = [1,2,3,4,5,6,7]
const [arr1, arr2] = _.chunk(mainArr, _.round(mainArr.length / 2));

Solution 6 - Javascript

You can also use underscore/lodash wrapper:

var ar = [1,2,3,4,5,6];
var p1 = _.first(ar, 4);
var p2 = _.rest(ar, 4);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser811433View Question on Stackoverflow
Solution 1 - JavascriptTJHeuvelView Answer on Stackoverflow
Solution 2 - JavascriptMark AmeryView Answer on Stackoverflow
Solution 3 - JavascriptmamooView Answer on Stackoverflow
Solution 4 - JavascriptMustkeem KView Answer on Stackoverflow
Solution 5 - JavascriptMichał WojasView Answer on Stackoverflow
Solution 6 - JavascriptmasterspambotView Answer on Stackoverflow