Sometimes, we want to split array into two arrays with JavaScript.
In this article, we’ll look at how to split array into two arrays with JavaScript.
How to split array into two arrays with JavaScript?
To split array into two arrays with JavaScript, we can use the array slice
method.
For instance, we write
const arr = ["a", "b", "c", "d", "e", "f"];
const indexToSplit = arr.indexOf("c");
const first = arr.slice(0, indexToSplit);
const second = arr.slice(indexToSplit + 1);
to call indexOf
to get the index of 'c'
.
Then we call slice
with 0 and indexToSplit
to return an array with arr
entries from index 0 to indexToSplit - 1
.
Next we call slice
again with indexToSplit + 1
to return an array from index indexToSplit + 1
to the end of the arr
array.
Conclusion
To split array into two arrays with JavaScript, we can use the array slice
method.