EN
TypeScript - get subarray from array
0 points
In TypeScript it is possible to split array in following way.
This method takes start-index and limit-index (excluded index) as arguments.
xxxxxxxxxx
1
const array: any = [
2
1, 2, 3, 'text 1', 'text 2', 'text 3', true, false
3
4
// 0 1 2 3 4 5 6 7 <- positive indexes
5
// -8 -7 -6 -5 -4 -3 -2 -1 <- negative indexes
6
];
7
8
const subArray1: any = array.slice(0, 4); // [ 1, 2, 3, 'text 1' ]
9
const subArray2: any = array.slice(2, 4); // [ 3, 'text 1' ]
10
const subArray3: any = array.slice(4); // [ 'text 2', 'text 3', true, false ]
11
const subArray4: any = array.slice(-2); // [ true, false ]
12
const subArray5: any = array.slice(2, -4); // [ 3, 'text 1' ]
13
const subArray6: any = array.slice(-5, -2); // [ 'text 1', 'text 2', 'text 3' ]
14
15
console.log(subArray1);
16
console.log(subArray2);
17
console.log(subArray3);
18
console.log(subArray4);
19
console.log(subArray5);
20
console.log(subArray6);
21
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' ]