Transforming a one-dimensional array and a single variable into a fresh two-dimensional array

Hi there, I'm currently learning programming and facing some challenges with arrays in TypeScript. Here are the variables I have:

let nameList: string[] = ['a', 'b', 'c', 'd'];
    let postId: number = 1;

My objective is to create a new 2D array:

let newList: (string | number)[][] = [];

in which

newlist = [
      [a,1],
      [b,1],
      [c,1],
      [d,1]
    ]

I have attempted the following:

for (let i: number = 0; i < userList.length; i++) {
      newList[i][0].push(userList[i]);
      newList[i][1].push(insertID);
    }

Additionally,

for (let i: number = 0; i < userList.length; i++) {
      newList[i][0] = userList[i];
      newList[i][1] = insertID;
    }

If anyone could provide assistance on this matter, it would be greatly appreciated! Thank you!

Answer №1

let newArray: [string, number][] = users.map((user) => [user, userId]);

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

How can I access elements in an array without using a loop in PHP?

Can the substr() function be applied to every element in an array without the need for a loop? ...

Implementing RTKQuery queryFn in TypeScript: A comprehensive guide

Important update: The issue is now resolved in RTKQuery v2 after converting to TypeScript. See the original question below. Brief summary I am encountering an error while trying to compile the TypeScript code snippet below. Tsc is indicating that the r ...

Incorporate a random numerical value into every nested array document

This JavaScript function is designed to generate a unique random number and add it to all embedded documents. However, to achieve this, a distinct random number must be created for each embedded document. app.patch("/updatemany", async (req, re ...

Embed an image in an email using byte

Currently, I am exploring the process of working with images that flow from a website to a service and then finally end up in an email. My approach involves converting the image into base64 format, uploading it to my service, transforming it into a byte ar ...

Split the array into several arrays based on a specific threshold

I have a graph depicting an array [2,8,12,5,3,...] where the x axis represents seconds. I am looking to divide this array into segments when the y values stay 0 for longer than 2 seconds. For example, in this scenario the array would be split into 3 parts: ...

Transforming an Image to Grayscale using RGB array matrix in Java

I am currently in the process of developing an Image filter application and my goal is to transform a colored image into a grayscale image using an array matrix. Here is the code snippet I have so far: import java.awt.Color; import se.lth.cs.ptdc.images. ...

Arrange the elements in a column of a multi-dimensional array in descending order while maintaining their respective keys

I have an array that needs to be sorted based on the 'answer' value in each 'scores' array, from high to low. $array = [ 503 => [ 'scores' => [ 4573 => ['answer' => 100], ...

Tips for managing MemoryError warnings when working with extremely large arrays for visualizing a function with three variables

Given the function F(x1, x2, x3) with three independent variables x1, x2, and x3 in 1D array format, I intend to plot F (using the contour class) for specific values of x3. Below is a snippet of my code where I suspect an error may be occurring: N = 10000 ...

Parse a document and store the contents within an array using the C programming language

I've been attempting to read a specified file and transfer its lines into an array. Initially, I haven't been utilizing dynamic allocation for the variable (maze) that will contain the lines of the file. Here is my current progress. #include < ...

Encountering issues when verifying the ID of Angular route parameters due to potential null or undefined strings

Imagine going to a component at the URL localhost:4200/myComponent/id. The ID, no matter what it is, will show up as a string in the component view. The following code snippet retrieves the ID parameter from the previous component ([routerLink]="['/m ...

Looking for a streamlined method to retrieve values from nested arrays using PHP?

I have discovered some old code while working on a project that involves several arrays. I want to combine them into nested arrays and am looking for a simple way to loop through the contents of these nested arrays. If there is a better way to store this d ...

Opt for Object.keys() over .length when dealing with Firebase Objects

How can I update this snippet to use Object.keys()? It currently works well when the comment ids are numbers, but how can it be adapted to work with auto-generated ids from Firebase? (The data structure is provided below) ngOnInit() { this.route.param ...

How to eliminate file nesting in Visual Studio 2017

Is there a way to prevent certain file types from being nested within other files, such as .ts files not being nested beneath .html files? I came across this request, but has anyone found a solution to achieve this? ...

Using Linq to transform an array of booleans into an array of bytes

I have an array of boolean values that I need to convert into a byte array. bool[] items = { true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, true, false, false, false, ...

Creating a concatenated string from a multidimensional array in PHP

array(thisItem "Color", thisValue "red" ), array(thatItem "Ram", thatValue "4GB" ) ); Please transform the above multidimensional array into a string following this format thisItem=red&thatItem=4GB ...

Discover the complete amount from a receipt extracted using OCR technology in PHP

I am facing challenges with extracting the total amount paid by the user from a receipt string obtained via an API vision. Here is an example: $testo2 = "Del burger Sr Via Carlo del Prete 106/d 50127 FIRENZE C.F. E P.IVA 08380120482 BRUNCH MAMMAMIA ONION ...

The MatInput value will only display after the page is reloaded or refreshed

After refreshing the page, a matInput field displays a value or result that was previously hidden. https://i.stack.imgur.com/q9LQI.png By selecting or highlighting within the matInput, the value or result becomes visible. https://i.stack.imgur.com/SqaLA.p ...

The Angular 2 view appears on the screen before the data finishes loading in the ngOnInit

Utilizing the github API in my angular 2 application, I encounter an issue where the view renders before ngOnInit has finished loading data. This leads to a Cannot read property of undefined error. The relevant portion of my code is as follows: ngOnInit() ...

Iterate through an array of objects using underscores, make alterations to specific objects, and eliminate other objects

Let's say I have an array of objects: [{"month":"03-2016","isLate":"N","transactionCount":4,"transactionAmount":8746455},{"month":"05-2016","isLate":"N","transactionCount":5,"transactionAmount":-40004952945.61},{"month":"06-2016","isLate":"N","transa ...

What is the best way to sort a union based on the existence or non-existence of a specific

My API response comes in the form of a IResponse, which can have different variations based on a URL search parameter. Here is how I plan to utilize it: const data1 = await request<E<"aaa">>('/api/data/1?type=aaa'); const d ...