A two-dimensional array is to be extended (No new one is to be created):
let array:number[][] = [
[5, 6],
];
For this we have two more two-dimensional arrays a1
and a2
:
let a1:number[][] = [[1, 2], [3, 4]];
let a2:number[][] = [[7, 8], [9, 10]];
The goal is now to insert a1
at the beginning and a2
at the end of array
:
array.unshift(a1);
array.push(a2);
The syntax is not permitted and the following errors occur:
Argument of type 'number[][]' is not assignable to parameter of type 'number[]'.
Type 'number[]' is not assignable to type 'number'.
The expected result is as follows:
[
[1, 2],
[3, 4],
[5, 6],
[7, 8],
[9, 10]
];
Does TypeScript/Javascript provide a way to insert the arrays without having to iterate and unshift/push element by element?
Please not:
Since the existing array can become very large, I would like to avoid copies (e.g. by concat or something similar).
2
Answers
why not sort the array after adding new element using
array.sort
You’re almost there. You just need to use the spread syntax.
TypeScript Playground