skip to Main Content

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


  1. why not sort the array after adding new element using array.sort

    let array = [
        [5, 6],
    ];
    
    let a1 = [[1, 2], [3, 4]];
    let a2 = [[7, 8], [9, 10]];
    
    array.unshift(...a1);
    array.push(...a2);
    
    array = array.sort((a, b) => a[0]-b[0])
    console.log(array);
    Login or Signup to reply.
  2. You’re almost there. You just need to use the spread syntax.

    let array: number[][] = [[5, 6]];
    
    let a1: number[][] = [
      [1, 2],
      [3, 4],
    ];
    let a2: number[][] = [
      [7, 8],
      [9, 10],
    ];
    
    array.unshift(...a1);
    array.push(...a2);
    
    console.log(array);
    // [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] 
    

    TypeScript Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search