Guide to converting a two-dimensional square matrix stored as a one-dimensional array in JavaScript

My inquiry is similar to the one linked below, however, I am seeking a solution using JavaScript

How to Transpose 2D Matrix Stored as C 1D Array

In essence, I have a square matrix in two dimensions

1 2 3
4 5 6
7 8 9

This matrix is stored like this

let anArray = [1 ,2, 3, 4, 5, 6, 7, 8, 9]

Is there a way to transpose this matrix so that the order of elements in my source array changes according to the following pattern?

let newArray = [1, 4, 7, 2, 5, 8, 3, 6, 9] 

Answer №1

To create a new array based on the dimension of an existing array, you can map items to specific indexes.

var originalArray = [1 ,2, 3, 4, 5, 6, 7, 8, 9],
    length = Math.sqrt(originalArray.length),
    newArray = originalArray.map((_, index, arr) => arr[(index % length) * length + Math.floor(index / length)]);
    
console.log(newArray.join(' '));

Answer №2

The technique mentioned in the provided answer can also be applied successfully in JavaScript.

For a 3 x 3 matrix:

const numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];

let newMatrix = [];
for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    newMatrix[3 * i + j] = numberArray[3 * j + i];
  }
}

console.log(newMatrix);

For an N x N matrix, simply replace the occurrences of 3 with N.

This approach eliminates the need for division and integer division, and it is expected to perform well with a decent optimizer. Initializing the new array with

let newMatrix = new Array(9);

or

let newMatrix = new Array(N * N);

can be considered, but it is recommended to profile the code before implementing such "optimizations."

Answer №3

let newArray1 = [];
let newArray2 = [];

for(let a=0; a<matrix.length; a++) {
    for(let b=0; b<matrix[a].length; b++) {
        newArray1.push(matrix[a][b]);
    }
}

for(let b=0; b<matrix[a].length; b++) {
    for(let a=0; a<matrix.length; a++) {
        newArray2.push(matrix[a][b]);
    }
}

Answer №4

To optimize your matrix, set a maximum "width" and organize it into a new array sequentially with an offset of 1 for each iteration.

function transformMatrix(data, width) {
  if (width === void 0) {
    width = 1;
  }
  var t = 0;
  var transformedArray = [];
  while (t < width) {
    for (var index = t; index < data.length; index += width) {
      transformedArray.push(data[index]);
    }
    t++;
  }
  return transformedArray;
}
//TEST
var originalArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var transformedResult = transformMatrix(originalArray, 3);
console.log(originalArray.join());
console.log(transformedResult.join());

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

Executing gruntfile from the devDependencies module

Currently, I am testing out a .js framework. Within my package.JSON file, specifically inside devDependencies, I have the following: "devDependencies": { "myFramework": "https://github.com/myRepo/myFramework/tarball/master", "grunt": "~0.4.2", ...

Is it possible to translate the content of the page into English and French simply by clicking on the designated buttons?

As I dive into working with knockout, I am still in the learning process. Currently, I have a dropdown code where selecting English translates the entire page to English and selecting French translates it to French without any issue. I believe this functio ...

encountering a problem while trying to run `npm install react-native-modal-datetime-picker` in the terminal

I've encountered an issue while working on my app where I keep getting errors when trying to install the react-native-modal-datetime-picker package, as well as other date time picker packages like @react-native-community/datetime-picker The specific ...

Python Error: Array Index Mismatch causing ValueError

My current task involves writing a method in Python that converts an RGB image to grayscale using the "average method," where I calculate the average of the three colors (not the weighted or luminosity method). The goal is to display the original RGB image ...

When referencing an object in AngularJS that is defined within the $scope, it is important to

Imagine having a NameController implemented in AngularJS. You can define variables like so: this.name = 'Joe'; Alternatively, you could use: $scope.name = 'Joe'; I have a preference for accessing all variables using object notation: ...

Can you explain the different types of dynamic page props available in a Next.js application?

Is there a specific type available in Next.js 14 that I can use to replace the "any" type in the TypeScript code snippet below, for my dynamic route? export default async function DetailProduct({ params }: any) { const { imageAddress, title, price } = ...

Cypress - Mastering negative lookaheads in Regular Expressions

While experimenting with Cypress, I encountered an issue regarding a filter test. The goal is to verify that once the filter is removed, the search results should display values that were filtered out earlier. My attempt to achieve this scenario involves ...

Automatically update div content using AJAX in a different approach

In my situation, I am facing a unique challenge compared to other queries. I have a div element with the following code <div id="ondiv"><?php ?></div> Within this PHP section are details of people who are currently online. Ideally, when ...

Allow Vue to handle the registration of the datepicker event

Is there a way to notify Vue when the datepicker changes the selected date? new Vue({ el: '#app', data: { termin: '' }, computed: { }, methods: { } }) This is just an input field: <div id="app"> <div c ...

Error: The dynamic selection function is experiencing an issue where it is unable to read the "map" property of an undefined

Currently, I am in the process of creating a React component that includes the usage of a select HTML input. The implementation is defined as shown below: <select className="form-control-mt-3" id="clientList" name="clientList" onChange={this.handleC ...

Filling form fields with array data (AngularJS)

Although I'm new to AngularJS, I'm struggling to figure out how to handle a list of arrays returned from the searchAll function. console 0: {mobile: "12345678", lastname: "last01", firstname: "first01"} 1: {mobile: "87654321", lastname: ...

Syntax error: Unexpected character encountered in JavaScript code

Although this question has been asked numerous times before, I have not been able to find a solution that applies to my specific situation. I am currently working on a chat system that involves sending and receiving messages. Here is my PHP code: < ...

{ Node.js and Express - Preventing Duplicate Requests } How to fix the issue of sending client-side requests twice

I'm currently diving into nodejs but this frustrating bug is driving me crazy!! Every time I try to make a POST request on my website, it ends up sending two requests instead of one. Initially, I suspected it was an issue with my connection to mongodb ...

Executing a post request after redirection in a node.js application

Can anyone help me with redirecting to a different URL from node js using the response.writeHead method? response.writeHead(301, {Location : <redirecturl>}) I want this redirection to be executed as a POST request, but it always defaults to GET. Is ...

How to use jQuery to change the background color of HTML table cells based on their content value

A dynamic table will be displayed based on the dropdown element selected. Below is a snippet of the code: <table id="myPlaneTable" class="table table-bordered"> <tr> <td style="width: 20%">Max speed</td> <td ...

Retrieving full data from the database using Backbone.js

I am facing an issue with my Django API response when trying to retrieve data in my Backbone.js frontend - only part of the data is being received. The current response structure is as follows: {"count":27,"next":"http://127.0.0.1:8000/messages/?page=2", ...

Implement an AJAX function to prompt a save dialog before initiating the download process

I'm currently programming an embedded device in C with a web server. One of the tasks I am working on is downloading files from this device. I need to download several files at once, so I've set up an AJAX request that uses a POST method and send ...

Issue with Axios in my React Application: Unidentified SyntaxError

As I attempt to connect to my database using axios, a frustrating error appears in my vsCode terminal. The error message reads as follows: SyntaxError: C:\Users\Kelly Owoju\Desktop\Kelly Bright\my-web-app\node_modules\a ...

Using React to pass a link into a reusable component

I am currently utilizing a reusable component in React where I pass mostly text and some props. One of the texts requires a linked word, but I am unsure how to embed that link within a string. Any suggestions on how to pass a string with embedded links? Th ...

The response from a Fetch API POST request comes back as a blank text

When I use fetch() to send a post request, the response is coming back empty. Here is my code: JS: async getTotalCompletionTimes() { var res = await fetch("repository/maps.php?method=getcompletiontimes&map="+this.getName(), {method: 'POST&ap ...