EN
JavaScript - split array into two based on index
0 points
In this article, we would like to show you how to split array into two based on index in JavaScript.
In this example, we use slice()
method to split array into two parts. The first part contains elements from index 0
to the specified index
(included), and the second part contains the rest of the array
.
xxxxxxxxxx
1
// index: 0 1 2 3 4
2
// | | | | |
3
var array = ['a', 'b', 'c', 'd', 'e'];
4
5
var index = 2;
6
7
var part1 = array.slice(0, index + 1);
8
var part2 = array.slice(index + 1);
9
10
console.log(part1); // [ 'a', 'b', 'c' ]
11
console.log(part2); // [ 'd', 'e' ]
In this example, we use slice()
method to split array into two parts. The first part contains elements from index 0
to the specified index
(excluded), and the second part contains the rest of the array
.
xxxxxxxxxx
1
// index: 0 1 2 3 4
2
// | | | | |
3
var array = ['a', 'b', 'c', 'd', 'e'];
4
5
var index = 2;
6
7
var part1 = array.slice(0, index);
8
var part2 = array.slice(index);
9
10
console.log(part1); // [ 'a', 'b', 'c' ]
11
console.log(part2); // [ 'd', 'e' ]