Retrieve the initial item from every sub-array within a master array

I'm working with arrays of arrays in TypeScript and I'd like to efficiently splice them to retrieve the first element of each sub-array. While it's not a particularly difficult task, I'm looking for a more succinct approach.

Below is an example in Python that demonstrates what I'm trying to achieve in TypeScript:

l1 = [[1,2],[3,4],[5,6]]
l2 = [i[0] for i in l1]
print(l2) # [1, 3, 5]

Answer №1

To manipulate each set of data within an array, you would utilize the map method. This involves passing a function to map that processes each sub-array and returns only its first value:

const input = [[1, 2], [3, 4], [5, 6]]
const output = input.map(subarray => subarray[0])
console.log(output) // => [1, 3, 5]

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

Vue.js - Resetting child components upon array re-indexing

I am working with an array of objects const array = [ { id: uniqueId, childs: [ { id: uniqueId } ] }, { id: uniqueId, childs: [ { id: uniqueId } ] }, ] and I have a looping structure ...

What steps can be taken to avoid an abundance of JS event handlers in React?

Issue A problem arises when an application needs to determine the inner size of the window. The recommended React pattern involves registering an event listener using a one-time effect hook. Despite appearing to add the event listener only once, multiple ...

Unable to locate the name even though it is not referenced in the typescript code

I'm attempting to retrieve a value inside an if statement structured like this: const Navbar = () => { const token = getFromStorage("token"); if (token) { const { data, error } = useQuery( ["username", token], ...

Change the format into a PHP array

In my workplace, I am confronted with a frustrating system that generates the following output: { party:"bases", number:"1", id:"xx_3039366", url:"systen01-ny.com", target:"_self", address:"Ch\u00e3o as Alminhas-Medas,Uteiros ...

Solving Ununiformed Shape in Python

Currently, I am trying to store data in a *.npy file using np.save. However, I am encountering the following error message: setting an array element with a sequence. The requested array has an inhomogeneous shape after 2 dimensions. The detected shape was ...

Supabase Type Generation Not Working as Expected

Every time I try to update my typing through the cli command, I keep getting this error message without much information for me to troubleshoot. 2023/03/01 09:34:01 Recv First Byte Error: failed to retrieve generated types: {"message":"Forbi ...

Angular - Resolving the issue of 'property does not exist on type' in TypeScript

Currently, I am following a video tutorial which also has a text version. Despite copying the code exactly as shown in the tutorial, I encountered the following error: Error TS2339: Property 'getEmployees' does not exist on type 'Employ ...

Modifying the original array will not affect the cloned array in C#

Presenting my original array named "gridPlacement" Original Array: "gridPlacement" Clone Array: "p1" class gridMemory { static public string[] gridPlacement = new string[9] {"x", "b", "c", "h", null, null, null, null, null }; } Introducing t ...

Nested Angular formArrays within formArrays

Currently working on inline editing in my project, I am attempting to patch value data from the server. Within my formArray for the accountNumbers array, I am encountering an issue when trying to change the value of inputs. The error message reads: Error: ...

Calculating the total of columns within a 2D jagged array using a void function without any return value

I am looking to modify my current code that currently only sums up complete columns and ignores the ones with incomplete data. I want it to add up all the numbers in each column, regardless of how many there are. For example: 1 2 3 4 1 2 3 1 2 1 I wou ...

Setting attributes within an object by looping through its keys

I define an enum called REPORT_PARAMETERS: enum REPORT_PARAMETERS { DEFECT_CODE = 'DEFECT_CODE', ORGANIZATION = 'ORGANIZATION' } In addition, I have a Form interface and two objects - form and formMappers that utilize the REPOR ...

Controlling the Output in Typescript without Restricting the Input

I am interested in passing a function as a parameter, allowing the function to have any number of parameters but restricting the return type to boolean. For example, a function Car(driver: Function) could be defined where driver can be ()=>boolean or ( ...

PANDAS: Transforming arrays into individual numbers in a list

My list is printing out as [array([7], dtype=int64), array([11], dtype=int64), array([15, 19, 23, 27, 31, 35, 39, 43, 47, 51, 55, 59, 63, 67], dtype=int64)] However, I want it to look like [7, 11, 15, 19, 23, ...] The issue arises when using pandas ...

Traversing a JSON array and populating a list in C#

Forgive me for asking a simple question, as I am still a beginner and struggling to solve my issue. string json = "{\"EmailList\":[{\"name\":\"John Bravo\",\"email\":&bsol ...

Having trouble with component loading in Angular 2 rc5?

I'm encountering an issue with the webpack prod build where components are not loading, and strangely there are no errors. The dev build, on the other hand, works perfectly fine. Here's a snippet of the code: freight-list.component.ts @Compone ...

Accessing array using mysqli

I am in the process of updating some old PHP code that utilized MySQL to now using MySQLi. The revised code I have is as follows: function mysql_fetch_full_result_array($result){ global $dbc; $table_result=array(); $r=0; while($row = mysqli_ ...

What is the reason for calling a multi-dimensional array when it is just a one-dimensional array of references to other one-dimensional

I'm familiar with array references, but in Perl, a multidimensional array is actually a one-dimensional array of references to other one-dimensional arrays. Can someone provide an example to help clarify this concept? ...

Is there a way in JavaScript to convert comma-separated values into an array?

I currently have a code that makes combo boxes hide or show, but I am concerned about what will happen if I add more categories. If I do add more categories, I would have to modify the code each time. My goal is to have a variable that can hold multiple v ...

Uploading Images to Imgur with Angular 4

As a newcomer to TypeScript, I am faced with the challenge of uploading an image to the Imgur API using Angular. Currently, my approach involves retrieving the file from a file picker using the following code: let eventObj: MSInputMethodContext = <MSIn ...

PHP: Mysterious Array Dilemma - The Missing Value conundrum!

I am encountering an issue with my array ($form) which is capturing information from $_POST: $form = $_POST['game']; Despite having the values in this array, I seem to be facing difficulties while working with them. To troubleshoot, I executed ...