To split an array in TypeScript, you can use the slice method or the destructuring assignment.
In this example,
numbers
with integer elements.slice
method to split numbers
into slices based on indices.slice
method returns a new array representing the sliced elements.const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const slices = [numbers.slice(0, 3), numbers.slice(3, 6), numbers.slice(6, 9)];
console.log(slices);
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
In this example,
numbers
with integer elements.numbers
into slices based on indices.const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const [slice1, slice2, slice3] = [numbers.slice(0, 3), numbers.slice(3, 6), numbers.slice(6, 9)];
console.log(slice1, slice2, slice3);
[ 1, 2, 3 ] [ 4, 5, 6 ] [ 7, 8, 9 ]
In this tutorial, we learned How to Split an Array in TypeScript language with well detailed examples.