0

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);

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.