Arranging the columns of a matrix

My dilemma involves a matrix (or multidimensional array) filled with non-unique values, similar to this example:

var matrix = [
                [1, 3, 2, 4, 1],
                [2, 4, 1, 3, 2],
                [4, 3, 2, 1, 4]
             ]

I am in need of sorting one row within this matrix while ensuring that the other rows maintain their original order to preserve the column organization.

//Sorted matrix based on row 0
var sorted_matrix = [
                      [1, 1, 2, 3, 4],
                      [2, 2, 1, 4, 3],
                      [4, 4, 2, 3, 1]
                    ]

If possible, I am looking for a solution using lodash.

Answer №1

To organize the data, create an array containing indices and sort it based on the values of matrix[0]. Then, generate a new array with the sorted elements.

var matrix = [[2, 4, 1, 3, 2], [1, 3, 2, 4, 1], [3, 2, 4, 1, 3]],
    indices = matrix[0].map((_, i) => i);

indices.sort((a, b) => matrix[0][a] - matrix[0][b]);

result = matrix.map(a => indices.map(i => a[i]));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To achieve matrix transposition using lodash, one approach is to utilize the zip function to transpose the matrix, followed by sorting it based on a specific row number using the sortBy function, and then finally re-transposing the matrix:

_.zip.apply(_, _.sortBy(_.zip.apply(_, matrix), row))

var matrix = [
    [1, 3, 2, 4, 1],
    [2, 4, 1, 3, 2],
    [4, 3, 2, 1, 4]
];
var row = 0;

result = _.zip.apply(_, _.sortBy(_.zip.apply(_, matrix), row));

console.log(result.join('\n'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>

Another way to write this operation is utilizing the rest parameter syntax:

_.zip( ..._.sortBy(_.zip( ...matrix), row));

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

Unable to retrieve jwt token from cookies

Currently, I am developing a website using the MERN stack and implementing JWT for authentication. My goal is to store JWT tokens in cookies. Despite invoking the res.cookie function with specified parameters (refer to the code below), I am facing difficul ...

Is it possible for the NextJS Client component to only receive props after rendering props.children?

Encountering a puzzling issue that has me stumped... In my setup, I have a server side component that fetches data and then sends it over to the client component, which is all pretty standard. Here's where things get weird... When I log the data on ...

The problem I'm facing is that all the data is being received, except for the name, when I start with the success

When I add parameters to the success URL, all data comes through, but when I add a name, it gives an error. I've noticed that if I remove the spaces between letters, it works fine. However, I want to make it function properly. Can you assist me with t ...

Creating dynamic Vue2 router links based on server-generated data

Currently, I am working on a Vue2 Single Page Application that fetches content from the server and allows clients to edit it in a Content Management System (CMS). The issue I'm facing is that when a user adds a relative link such as /about-us, Vue do ...

Creating a circle in SVG that cannot be scaled using Javascript

I'm working on a map project using JavaScript and SVG for drawing the lines. One feature I'd like to implement is the ability to search for a specific road, and if found, display a circle on the map. I understand how to draw a circle in SVG, bu ...

Tips for automatically closing a dropdown menu when it loses focus

I'm having some trouble with my Tailwind CSS and jQuery setup. After trying a few different things, I can't seem to get it working quite right. In the code below, you'll see that I have placed a focusout event on the outer div containing th ...

Put a cookie in place to deter users from returning to the website

Looking for a way to prevent access to my contest site once the form has been submitted. Is there a way to achieve this? Thanks in advance ...

Navigating to native script, the method for extracting an ID from a link is revealed

Is there a way to extract the unique identifier from this URL: I want to retrieve the code "11E89887FABBC1D" when clicking on the link. Any suggestions? ...

What is the best way to return JSON data in a compressed (gzip) format to an Ajax Request using Java?

When sending compressed JSON in response to an Ajax request from my Java program, I understand that I need to set the Content-Encoding in the Response Header to gzip. However, are there any additional steps I should take? ...

What is the best way to give stacked bar charts a rounded top and bottom edge?

Looking for recommendations on integrating c3.js chart library into an Angular 6 project. Any advice or suggestions would be greatly appreciated! https://i.sstatic.net/iiT9e.png ...

Black-colored backdrop for Mui modal

Currently working with a mui modal and encountering an issue where the backdrop appears as solid black, despite setting it to be transparent. I attempted to adjust the color to transparent, but the issue persists. ...

"Exploring the World Wide Web with JavaScript and Ajax in Internet

Is there a way to include a Javascript snippet at the end of some ajax content? It seems to be functioning properly in Firefox, but when I try it in Internet Explorer, the script is printed out without being executed. <script type="text/javascript"&g ...

Issue with Javascript redirect not working following form submission in combination with Asp Classic

After countless hours of research and experimentation, I find myself at a standstill. My web page is coded extensively, so I'll do my best to provide a concise summary. The core elements of my ASP CLASSIC page for creating tickets via a form are as f ...

By default, apply the active class to the initial element in the list and update the active class upon clicking in Next.js

As a newcomer to React, I am struggling with setting the active class in my CSS file. I have two classes, btn and active. My goal is to assign the active class to the first button by default and then switch it to the currently clicked button when interacti ...

The issue with Node.js router failing to process delete requests

My Node.js router is handling all methods well except for the DELETE method. I can't figure out why the delete request does not reach the router. The AJAX request seems to be functioning correctly. AJAX request: function ajaxHelper(url, onSuccessAr ...

The AngularJS Navbar is Bootstrapped

I'm currently working on a project where I need to make a bootstrap navbar show and hide html elements based on data retrieved from an angular controller. Below is the jade code snippet: div.navbar.navbar-fixed-top div.navbar-inner div.c ...

Issues with dependencies in npx create react app

After initiating a new react project with npx create-react-app client, I have encountered an issue where the react-scripts command is not found, preventing me from running the start script. Is there a way to resolve this problem? Furthermore, when attempt ...

One way to submit a value form in an iframe is by double clicking

I am looking to submit a value form in a frame that functions as described below: index.php <form action="iframe1.php" method="post" target="iframe1"> <input type="text" name="lala"> <input type="submit"> </form> <iframe name= ...

Displaying subsets of data based on the identifier of the primary array

In my JSON file, I have an array containing various categories and their respective subcategories. { "Women": [ { "id" : 1, "name" : "See All", &q ...

Creating a multitude of cubes by iterating through the pixel color data of getImageData in Three.js

Using a simple 3x3.png file to extract color/opacity data from, where each of the 9 pixels represents a different color/opacity level. The .png is supposed to be loaded onto an off-screen canvas, following which the 9 cubes are drawn in a 3x3 grid pattern ...