EN
JavaScript - get subarray from array
8 points
In this article, we would like to show you how to split the array in JavaScript.
This method takes the start-index and limit-index (excluded index) as arguments.
xxxxxxxxxx
1
var array = [
2
1, 2, 3, 'text 1', 'text 2', 'text 3', true, false
3
4
/*
5
0 1 2 3 4 5 6 7 <- positive indexes
6
-8 -7 -6 -5 -4 -3 -2 -1 <- negative indexes
7
*/
8
];
9
10
var subArray1 = array.slice(0, 4); // [ 1, 2, 3, 'text 1' ]
11
var subArray2 = array.slice(2, 4); // [ 3, 'text 1' ]
12
var subArray3 = array.slice(4); // [ 'text 2', 'text 3', true, false ]
13
var subArray4 = array.slice(-2); // [ true, false ]
14
var subArray5 = array.slice(2, -4); // [ 3, 'text 1' ]
15
var subArray6 = array.slice(-5, -2); // [ 'text 1', 'text 2', 'text 3' ]
16
17
console.log(subArray1);
18
console.log(subArray2);
19
console.log(subArray3);
20
console.log(subArray4);
21
console.log(subArray5);
22
console.log(subArray6);
Output (with NodeJS):
xxxxxxxxxx
1
[ 1, 2, 3, 'text 1' ]
2
[ 3, 'text 1' ]
3
[ 'text 2', 'text 3', true, false ]
4
[ true, false ]
5
[ 3, 'text 1' ]
6
[ 'text 1', 'text 2', 'text 3' ]