Rearrange an irregular matrix using JavaScript

I have a matrix that can vary in width depending on the results received from the server. Here is an example:

[undefined, undefined]
[1, 2, 3, 4]
[1, 2]
[undefined, undefined, undefined]
[1, 2, 3, 4, 5, 6]

My goal is to transform it into this format:

[undefined, 1, 1, undefined, 1]
[undefined, 2, 2, undefined, 2]
[undefined, 3, undefined, undefined, 3]
[undefined, 4, undefined, undefined, 4]
[undefined, undefined, undefined, undefined, 5]
[undefined, undefined, undefined, undefined, 6]

The height of the matrix should match the maximum width of the initial example. I tried using the code snippet I found online:

array.map((row, i) => array.map(col => col[i]))

However, this solution does not change the height of my matrix. I attempted to use two for loops but did not achieve the desired outcome. Any assistance would be greatly appreciated!

Answer №1

There are various methods to tackle this issue, as seen in other responses. Below is my approach, focused on reducing the number of iterations over the data set.

const data = [
  [undefined, undefined],
  [1, 2, 3, 4],
  [1, 2],
  [undefined, undefined, undefined],
  [1, 2, 3, 4, 5, 6],
];

// Determine the length of the longest array
const maxLen = data.reduce((max, {length}) => Math.max(max, length), 0);

// Create a new set of arrays
const result = Array.from({ length: maxLen }, (_, i) => data.map(col => col[i]));

console.log(result);

Answer №2

If your matrix is stored in the variable matrix,

const result = [];

const maxColumns = matrix.reduce((max, current) => {
    return (current.length > max) ? current.length : max;
}, 0);

// Iterating through each column
for (let i = 0; i < maxColumns; i++) {
    const transposedRow = [];

    // Iterating through each row in the current column
    for (const row of matrix) {
        transposedRow.push(row[i]);
    }

    result.push(transposedRow);
}

Answer №3

To achieve the desired outcome, follow these steps.

  1. Determine the maximum length.

  2. Normalize the data.

  3. Proceed with rotation.

Code comments have been included to highlight each segment of the process.

const input = [
  [undefined, undefined],
  [1, 2, 3, 4],
  [1, 2],
  [undefined, undefined, undefined],
  [1, 2, 3, 4, 5, 6]
];

// Find the maximum length
const maxLength = Math.max(...input.map(m => m.length));

// Normalize the input array
const normalizedInputs = input.map(m => 
  (new Array(maxLength)).concat(m).slice(-maxLength)
);

// Perform rotation on the normalized data
const output = (new Array(maxLength).fill(0)).map(
  (row, i) => normalizedInputs.map(col => col[i])
);

Answer №4

Here is a more effective approach:

const calculateMaxLength = (arr) => {
  let maxVal = 0

  for (const { length } of arr) maxVal = Math.max(maxVal, length)

  return maxVal
}

const transposeArray = (array, placeholder = undefined) => {
  const result = []
  const maxLength = calculateMaxLength(array)
  let row = 0

  for (const { length } = array; row < length; row++) {
    const innerArr = array[row]
    let col = 0

    for (const { length } = innerArr; col < length; col++) {
      result[col] ||= []
      result[col].push(innerArr[col])
    }

    for (; col < maxLength; col++) {
      result[col] ||= []
      result[col].push(placeholder)
    }
  }

  return result
}

const transposedArray = transposeArray(
  [
    [1, 2],
    ['a', 'b', 'c', 'd'],
  ]
)

console.log('Transposed Array:', transposedArray)

console.log('Original Array after Transposing back:', transposeArray(transposedArray))

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

What is the process for adding a download link to my canvas once I have updated the image?

Is it possible to create a download link for an image that rotates when clicked, and then allows the user to download the updated image? Any help would be appreciated.////////////////////////////////////////////////////////////////////// <!DOCTYPE ht ...

Switching from using fs.readFile to fs.createReadStream in Node.js

I have a dilemma regarding my code, which involves reading an image from a directory and sending it to index.html. My goal is to replace fs.readFile with fs.createReadStream, but I am struggling to figure out how to implement this change as I cannot seem ...

The concept of PHP mysqli empty array

Having trouble populating my HTML with fetched array data. Instead of seeing results, I'm only getting blank spaces. Can someone help me figure out what's going on? <?php require_once("php/loader.inc.php"); include("php/header.php"); include( ...

What methods do certain API services use to accept Authorization headers from any source?

Payment processing platforms like Stripe and Square provide the capability to include your API key in an Authorization header as a Bearer token. However, my understanding is that allowing credentials, such as the Authorization header, from all origins is ...

Loop through an array containing strings, not objects

I am trying to iterate over an array that consists of strings, not objects. Despite my attempts to implement solutions from other Stack Overflow answers, I have been unable to make it work. The array: var_dump(`$myids`); array(3) { [0]=> string(2) ...

How to create buttons in React to increase and decrease a value?

Just starting out with React and attempting to create a ticket counter. The goal is to increase or decrease by 1 based on the direction of the arrow clicked. However, I'm facing an issue where nothing is displaying on my webpage. Any ideas on what mig ...

Creating pathways in AJAX with Rails

Issue at hand: undefined variable article_id. The objective: Setting up the correct route for AJAX and Rails. What I require: The format articles/1/comments/2. Main goal: To specifically load comment through AJAX, not article. In the current AJAX scrip ...

How can we address this perpetual loop issue with useEffect in the most effective manner?

I've recently developed an application that makes use of the pokeAPI to retrieve information about pokemons. In this app, I maintain a global array called "myPokemons" which stores the pokemons that I want to display. To achieve this, I created a func ...

A guide on properly formatting an Array of Objects in JavaScript based on the contained data

My goal is to create an Array of Object that groups the same weekday data into one object. For example, if we have weekday:1 in five objects, the desired output would be: { ..., weekDay: 1, repeated: 5 } While I can achieve this by hard coding a solution ...

Changing a class and audio and storing it using browser's local storage

The challenge I am facing: I am currently working on a feature for my website that allows users to toggle the volume on/off and have that setting persist across different pages. Specifically, I want the user's volume preference to be saved when they n ...

What is the best way to position the content on this page so that there is no horizontal scroll

Hey there! I'm currently working on a simple website using CSS flexbox, but I'm encountering an issue with my layout in About.vue. For some reason, this component is stretching out with a horizontal bar, even though it's only placed within t ...

Decoding JavaScript content with Python

Currently, I am dissecting this specific portion of HTML <script type="text/javascript"> var spConfig = new Product.Config({"attributes":{"150":{"id":"150","code":"size_shoe","label":"Schuhgr\u00f6\u00dfe","options":[{"id":"494","label ...

Calculate the number of checked checkboxes using JQuery

Can someone help me figure out how to get the count of checked checkboxes from the code sample below? Thanks, Digambar K. ...

Exploring the power of Knockout Js and Typeahead libraries

https://i.stack.imgur.com/38iZc.png Hello experts in Knockout and typeahead, I am receiving suggestions from the typeahead js as shown above. I have my data supplied in an array format var itemsRandom= ['Apple', 'Ball','Ape&apos ...

Setting up a Node.js project in your local environment and making it

I need help installing my custom project globally so I can access it from anywhere in my computer using the command line. However, I've been struggling to make it work. I attempted the following command: npm install -g . and some others that I can&ap ...

Determining the elapsed time using Momentjs

I need assistance with a NodeJS project where I am trying to determine if a specific amount of time (like 1 hour) has passed since creating an object. My project involves the use of MomentJS. For example, if moment(book.createdAt).fromNow() shows 2 hours ...

Best method for removing CrosshairMove event listener in lightweight charts

As per the documentation, using unsubscribeCrosshairMove allows us to remove a handler that was previously added with subscribeCrosshairMove. Our objective is to use unsubscribe... to eliminate previous handlers before re-subscribing with subscribe... af ...

I want to establish the identical response output field name in NestJS by utilizing the @Expose decorator from class-transformer

My Entity definition currently looks like this: export class ItemEntity implements Item { @PrimaryColumn() @IsIn(['product', 'productVariant', 'category']) @IsNotEmpty() itemType: string; @PrimaryColumn() @IsU ...

Tips for successfully incorporating a jQuery plugin into your React project

I'm attempting to incorporate the Air Datepicker library by t1m0n into my React application, but I'm encountering difficulties. import React from 'react'; import AirDatepicker from 'air-datepicker'; class Datepicker extend ...

Link Array with Google Charts

I've been struggling for a long time to connect this array to a Google chart with no success. I would really appreciate some assistance in identifying what mistake I've made. I have created a jsfiddle where the array appears to be correct, and wh ...