Ways to break down a collection of multiple arrays

Looking to transform an array that consists of multiple arrays into a format suitable for an external API.

For example:

[ [44.5,43.2,45.1] , [42, 41.2, 48.1] ]

transforming into

[ [44.5,42], [43.2,41.2] , [45.1, 48.1] ]

My current code attempts this transformation but is not functioning as expected

var newArr= [];
var tempArr= [];

for(var key in data){
    tempArr.push(finalArr[key][key])
    newArr.push(tempArr)
 }

Is there a simpler way to achieve this without using loops? I thought about potentially using a map function, but unsure of how to apply it here.

Answer №1

One way to rearrange arrays is by using reducing and mapping the values.

This method can be applied to arrays of any length.

const transpose = array => array.reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), []);

console.log(transpose([[44.5, 43.2, 45.1], [42, 41.2, 48.1]]));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

const matrix = [
  [10, 20, 30],
  [40, 50, 60]
];
const combinedArray = matrix[0].map(function (element, index) {
  return [element, matrix[1][index]];
});
console.log(combinedArray);

Ensure that the arrays being combined are of equal lengths before performing the operation.

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

Mastering the art of bi-directional data binding with nested arrays in Angular

Imagine you have a to-do list with various tasks, each containing multiple subtasks. You want the ability to change the subtask data, but why is Angular not properly two-way binding the data for the subtasks? HTML <div *ngFor="let task of tasks"> ...

When referencing a particular React commit in package.json, it may result in the installation of react-tools instead of react itself

After including the following line in my package.json: "react": "git://github.com/facebook/react.git#08e4420019f74b7c93e64f59c443970359102530" When I execute npm install, I notice that node_modules/react-tools has been installed instead of node_modules/r ...

Guide on incorporating a YouTube iframe in React with Typescript

It appears that Typescript is posing some challenges for me in this scenario. Here's the code snippet I am trying to include: <iframe width="560" height="315" src="https://www.youtube.com/embed/BLAH?showinfo=0" frameBorder="0" ...

Having trouble getting AngularJS ngCloak to function properly?

My post category page is supposed to display a message if there are no posts. However, the HTML appears briefly when the page loads and then hides. I thought using ngCloak would solve this issue, but it doesn't seem to be working for me. Here's t ...

Seeking assistance in configuring a dynamic payment amount feature on Stripe using Node.js

As a newcomer to node and javascript, I'm seeking guidance on how to proceed with the code below. I have copied it from the Stripe documentation, but I am unsure about the function for the commented token. Initially, everything was working fine with t ...

Understanding the complexity of defining the type of a function can be challenging. If you're tasked with a complicated function, determining its type

Let's break it down: Dict is defined as { [key: string]: () => any } The desired return value is represented by X I am attempting to create a type for a function that: Takes in a dictionary Dict T Returns an X Now, X also functions as a functio ...

How can one smoothly rewind X frames in a video or animation on a webpage without experiencing lag?

For my thesis presentation, I decided to make it available online as a video with custom controls resembling a powerpoint slideshow. The challenge I encountered was with transitions between slides in an animated video. Certain transitions needed to loop fo ...

Parent controller was not in command before Child执行

When working with a parent view and a child view, I encounter an issue with accessing a json file. In the parent view, I retrieve the json file using the following code: $scope.services = Services.query(); factory('Services', function($reso ...

Issue with timestamp in the Instagram API call to retrieve media using AJAX (GET /media/search)

My API call is returning a 400 bad request error message: {"meta":{"error_type":"APIInvalidParametersError","code":400,"error_message":"invalid parameters-check the max\/min-timestamps, if you supplied them"}} Even though my request appears to be co ...

Which is better in Angular2: defining default property values in the constructor or inline?

When it comes to creating an object class in Angular 2, the common dilemma is whether to initialize values inline or within a constructor. But what exactly is the difference between the two approaches? export class Foo { id: string; name: string = &ap ...

How can I designate the file name when using Ajax to export in Excel formatting?

Can you help me with the code to set a specific filename for downloading an Excel file? if(comp_id != "Select Company") { $.ajax({ url: 'includes/export.php', data: { action: 'compreport', 'comp':comp_i ...

Efficiently loading data in a table with a universal filter feature using Angular with PrimeNG

Recently, I managed to set up a datatable with the functionalities of both Lazy loading and global filter. Utilizing PrimeNG components for this implementation was a breeze. However, an issue surfaced where the global filter ceased to function when lazy lo ...

What is the best way to implement the 'setInterval' function in this code to effortlessly fetch forms or data on my webpage without any need for manual refresh?

I am using ajax and javascript to fetch a modal on another page or in a separate browser. While I am able to retrieve the modal, I require the page to refresh before displaying the modal. I have come across suggestions to use the setInterval function but I ...

I designed my higher-order component to allow for dual invocations. How can I integrate Redux within this framework?

I have implemented my higher-order component (HOC) in such a way that it can be invoked twice, emphasizing the concept of "functional programming". However, I am facing challenges in connecting Redux to access state and certain functions. I would greatly ...

To achieve the desired format, where should I press or manipulate the information?

I need help with manipulating arrays to generate a specific JSON file structure. I've made some progress but got stuck at this point: var T_nn_IN = document.getElementById('datatablenewname'); var tabledata_newname_initialname = []; ...

Combine the object with TypeScript

Within my Angular application, the data is structured as follows: forEachArrayOne = [ { id: 1, name: "userOne" }, { id: 2, name: "userTwo" }, { id: 3, name: "userThree" } ] forEachArrayTwo = [ { id: 1, name: "userFour" }, { id: ...

Issue with clearTimeout function not functioning properly on keyup event in iFrame

While there may be many similar questions out there, I have yet to find a solution that works for me. Currently, I am developing a WYSIWYG editor and I want it to save when the user performs a keyup action. However, I do not want it to update after every ...

Javascript - The art of accessing an anonymous array

I'm trying to extract data from an API, but I've run into a snag. There's a list without a name attached to it, making it impossible for me to access the values inside. Here's a simplified example of what I mean: (Here is the JSON stru ...

Rendering the Next.js Link tag on the page is displaying as [object Object]

Hey there! I'm currently working on creating breadcrumbs for a webpage and this is what the breadcrumb array looks like: const breadcrumbs = ['Home', "Men's Top", 'Winter Jacket'] Now, in JSX with Next.js, I am att ...

Understanding the process of parsing JSON response using JavaScript

I am facing an issue with reading a JSON object in JavaScript. I have received this JSON object as a response and now I need to create a jstree based on it. Here is my JavaScript code: var repoId = $('#frmHdnV').val(); // variable to hold req ...