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.
8 Answers
Use slice, as such:
var ar = [1,2,3,4,5,6];
var p1 = ar.slice(0,4);
console.log({p1});
var p2 = ar.slice(4);
console.log({p2});
5 Comments
Xanlantos
what happens with arrays that are too short [1,2.3].slice(4) ?
Kyle Soeltz
@Xanlantos it will return an array that is identical to the original.
Zain Syed
@KyleSoeltz I believe that is inaccurate and it actually returns an empty array. I've just tested this. This behavior seems preferable to me.
Kyle Soeltz
@ZainSyed Ah yes you are correct. I misread the question and was thinking [1,2,3].slice(0,4) which will return an identical array. [1,2,3].slice(4) will return an empty array.
Syed M. Sannan
I believe in most cases, you should use splice instead because slice does not reset the index.
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"]
Comments
use slice:
var bigOne = [0,1,2,3,4,5,6];
var splittedOne = bigOne.slice(3 /*your Index*/);
Comments
const splitAt = (i, arr) => {
const clonedArray = [...arr];
return [clonedArray.splice(0, i), clonedArray];
}
const [left, right] = splitAt(1, [1,2,3,4])
console.log(left) // [1]
console.log(right) // [2,3,4]
const [left1, right1] = splitAt(-1, [1,2,3,4])
console.log(left1) // []
console.log(right1) // [1,2,3,4]
const [left2, right2] = splitAt(5, [1,2,3,4])
console.log(left1) // [1,2,3,4]
console.log(right1) // []
Some benefits compared to other solutions:
- You can get the result with a one liner
- When split index is underflow or overflow, the result is still correct.
slicewill not behave correctly. - It does not mutate the original array. Some
splicebased solutions did. - There is only 1
spliceoperation, rather than 2sliceoperations. But you need to benchmark to see if there is actual performance difference.
1 Comment
Abel Chipepe
I find this answer way cooler, clone the array and then perfom the operations. Great work.
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);
1 Comment
jelder