changing a one-dimensional array into a two-dimensional array using TypeScript

I need help transforming a flat array into a 2D array, like this:

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

My desired output is:

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

While researching, I came across this helpful question. However, it's in javascript and I encountered an error when trying to declare the types for "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);

Answer №1

When working with TypeScript, errors may occur when the type of a variable cannot be determined, as seen in the case of the matrix variable.
code:

function listToMatrix(list: number[], elementsPerSubArray: number) {
  var matrix: number[][] = []; // Be sure to 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:

https://i.sstatic.net/uFbTA.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating object-oriented classes dynamically in C# with a loop

In my project, I am working with a class called player: class player { public string name; public int rating; { The quantity of player classes needed is determined by the user-supplied value numberOfPlayers. Initially, I thought about using a for lo ...

What are the steps for installing the latest version of popper, v2?

When you run the following command: npm install popper.js --save You will receive a warning message that says: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="81f1eef1f1e4f3afebf2c1b0afb0b7afb0">[email& ...

Employing v-btn for navigating to a different route depending on whether a specific condition is satisfied

Is there a way to prevent this button from redirecting to the specified URL? I want to implement a validation check in my method, and if it fails, I need to stop this button from performing any action. Any suggestions or assistance would be highly apprec ...

Accessing information from an Odata controller in Angular2

Greetings as a first-time question asker and long-time reader/lurker. I've been delving into learning angular2, but I'm facing some challenges when it comes to retrieving data from an odata controller. In my simple Angular 2 application, I'm ...

What is the reason behind the inefficacy of using current() in conjunction with foreach() in PHP

I am seeking to grasp the meaning behind this piece of code : $array = [0, 1, 2]; foreach ($array as &$val) { var_dump(current($array)); } Upon running the code in PHP 5.6, the output was int(1) int(2) bool(false), while in PHP 7, it was int(0) i ...

Player script does not contain a valid function signature according to XCDYouTubeKit

I need help finding a regular expression to match these Youtube links. I'm feeling lost and unsure of what to do. https://www.youtube.com/watch?v=2BS3oePljr8 http://www.youtube.com/watch?v=iwGFalTRHDA http://www.youtube.com/watch?v=iwGFalTRHDA& ...

Transform data into proper JSON structure in a React JS application

I am facing an issue with the object structure below: { Inputs : { key : value, key: valu }}, My goal is to convert it into a JSON format using JSON.stringify(Inputs). However, the resulting format is incorrect as shown below, causing my ...

Navigating through the URL using an AJAX request with jQuery

After seeking assistance on how to loop through data in a json file from an asynchronous AJAX call in jquery using callback functions (Looping through AJAX and callbacks in jquery), I received valuable help. Now, I am curious about the possibility of loo ...

Tips for concealing the body description on the homepage of a blogger website

I want to conceal this description This is my blog and I am facing an issue where I need to hide the description on the home page. I have tried using color:white which worked initially, but when I moved the description to the top or left, the black backgro ...

Guide on creating an AngularJS application using Yesod

After successfully developing a small app using Yesod, I am now focused on adding improved interaction to it with the help of AngularJS. Currently, it appears that the AngularJS support in Yesod is still in an experimental phase. Additionally, the documen ...

Check the radio box corresponding to the adjacent label

As a hobby, I have been exploring ways to automate questionnaires that I used to manually deal with for years. It has always intrigued me how best to streamline this process, and now I am taking the opportunity to indulge in my passion and enhance my JavaS ...

Steps to initiate my selenium-standalone server: Execute the command "selenium-standalone start"

I'm currently facing a challenge while trying to execute a test script in WebDriverIO. After cloning the code from wdio-cucumber-framework, I am unable to get selenium-standalone to start properly. The error message indicates an issue with geckodriv ...

Leveraging jquery within an XML document in a SAPUI5 fragment

I'm experiencing a minor issue with my app. I have an Image property that has an empty background, and I want to add a class to it when clicked. However, my controller is unable to detect classes or IDs of properties in the view.xml document. Is there ...

Not verifying the argument type in Typescript makes the function generic in nature

I was initially under the impression that TypeScript would throw an error due to passing the incorrect number of elements in EntryPoints, but surprisingly, no error occurred. function createContext<T>(defaultValue: T): T[] { return [defaultValue] ...

Avoid using sleep statements in Webdriverjs to prevent stale element reference issues

I've come across a block of code that utilizes action sequences to execute the following steps: click on a link that directs to a specific page wait for an input field to become visible on the page click on the input field clear any existing text in ...

Is there a jQuery or Javascript alternative to CSS Counter?

Can a counter be implemented that changes the text of a tag directly using jQuery/Javascript? For example, if there were two tags like this: <a>hello</a> <a>bye</a> After executing the jQuery/JS function, the result would be: < ...

What is the best way to incorporate Vue.js component dependencies into a multi-page application (MPA

When working with a multiple page app, incorporating a component inside another component can be challenging, especially without using a build system. $ npm install sagalbot/vue-select <template> <div id="myApp"> <v-select :value.sy ...

Having trouble loading my script in the frontend plugin?

After much testing, I have discovered that when I place this code before the get_header() function, the script is successfully loaded. However, when I move it after the get_header() function, it no longer works as intended. It's important to note that ...

What is the best way to send data from a header component to a separate container component?

Utilizing React-router-dom, I am able to seamlessly switch between components in the following setup: <Router> <div> <Header /> <NavigationBar /> <Switch> <Route exact path ...

Typescript: How to Ensure Tuple Type is Explicit and Not Combined

I have a code snippet that defines a person object and a function to get its values: const person = { name: "abc", age: 123, isHere: true }; const getPersonValues = () => { return [person.name, person.age, person.isHere]; }; const [n ...