Languages
[Edit]
EN

TypeScript - get subarray from array

0 points
Created by:
Welsh
902

In TypeScript it is possible to split array in following way.

1. Array split method example

This method takes start-index and limit-index (excluded index) as arguments.

const array: any = [
    1, 2, 3, 'text 1', 'text 2', 'text 3', true, false

//  0  1  2      3         4         5       6     7    <- positive indexes
// -8 -7 -6     -5        -4        -3      -2    -1    <- negative indexes
];

const subArray1: any = array.slice(0, 4);   // [ 1, 2, 3, 'text 1' ]
const subArray2: any = array.slice(2, 4);   // [ 3, 'text 1' ]
const subArray3: any = array.slice(4);      // [ 'text 2', 'text 3', true, false ]
const subArray4: any = array.slice(-2);     // [ true, false ]
const subArray5: any = array.slice(2, -4);  // [ 3, 'text 1' ]
const subArray6: any = array.slice(-5, -2); // [ 'text 1', 'text 2', 'text 3' ]

console.log(subArray1);
console.log(subArray2);
console.log(subArray3);
console.log(subArray4);
console.log(subArray5);
console.log(subArray6);

Output (with NodeJS):

[ 1, 2, 3, 'text 1' ]
[ 3, 'text 1' ]
[ 'text 2', 'text 3', true, false ]
[ true, false ]
[ 3, 'text 1' ]
[ 'text 1', 'text 2', 'text 3' ]
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join