skip to Main Content

I have a flat array like this

['-', '-', '-', '-', '-', '-', '-', '-', '-']

and I want to convert it to be 2D like this

[
  ['-', '-', '-'],
  ['-', '-', '-'],
  ['-', '-', '-']
]

I saw this question but it is in javascript and I am getting error on declaring types of the "list" and "elementsPerSubArray"

// declaring type of list and elementsPerSubArray
function listToMatrix(list: number[], elementsPerSubArray: number) {
    var matrix = [], i, k;

    for (i = 0, k = -1; i < list.length; i++) {
        if (i % elementsPerSubArray === 0) {
            k++;
            matrix[k] = [];
        }
        // here I am facing error says " Argument of type 'number' is not assignable to parameter of type 'never' "
        matrix[k].push(list[i]);
    }

    return matrix;
}

var matrix = listToMatrix([1, 2, 3, 4, 4, 5, 6, 7, 8, 9], 3);

2

Answers


  1. TypeScript is giving you an error because it can’t figure out the type of the matrix variable.
    code:

    function listToMatrix(list: number[], elementsPerSubArray: number) {
      var matrix: number[][] = []; // Specify the type as number[][]
    
      for (let i = 0, k = -1; i < list.length; i++) {
        if (i % elementsPerSubArray === 0) {
          k++;
          matrix[k] = [];
        }
        matrix[k].push(list[i]);
      }
    
      return matrix;
    }
    
    var matrix = listToMatrix([1, 2, 3, 4, 4, 5, 6, 7, 8, 9], 3);
    console.log(matrix);
    

    Output:

    enter image description here

    Login or Signup to reply.
  2. Glad to answer your question.

    I have found some errors in your code.
    In your code, you’ve declared the list parameter as an array of numbers ( number[] ), but you’re passing in an array of strings ( [‘-‘, ‘-‘, ‘-‘, ‘-‘, ‘-‘, ‘-‘, ‘-‘, ‘-‘, ‘-‘] ). To fix this, you should update the type declaration for list to be an array of strings ( string[] ).

    Here’s the updated code:

    function listToMatrix(list: string[], elementsPerSubArray: number) {
        var matrix = [], i, k;
    
        for (i = 0, k = -1; i < list.length; i++) {
            if (i % elementsPerSubArray === 0) {
                k++;
                matrix[k] = [];
            }
            matrix[k].push(list[i]);
        }
    
        return matrix;
    }
    
    var matrix = listToMatrix(['-', '-', '-', '-', '-', '-', '-', '-', '-'], 3);
    

    Hope this would help you.

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