JavaScript: Arranging the columns in a two-dimensional array based on the elements in a specific row

Here is an example of an array:

 [[ 'Table', 'Column A', 'Column B', 'Column C'],
  [ 'Row 1', 10, 5, 7 ],
  [ 'Row 2', 20, 15, 50 ],
  [ 'Row 3', 8, 13, 3 ]]

I am looking to rearrange the columns based on values in 'Row 1' to prioritize the most important column. The desired result is:

 [[ 'Table', 'Column A', 'Column C', 'Column B'],
 [ 'Row 1', 10, 7, 5 ],
 [ 'Row 2', 20, 50, 12 ],
 [ 'Row 3', 8, 3, 13 ]]

Observe how column positions have changed for C and B.

Any suggestions on how to achieve this using JavaScript?

Answer №1

Follow these steps :

let arrayData = [[ 'Table', 'Column A', 'Column C', 'Column B'],
         [ 'Row 1', 10, 7, 5 ],
         [ 'Row 2', 20, 50, 12 ],
         [ 'Row 3', 8, 3, 13 ]];


function switchColumns(array, col1, col2) {
    for (let i=0;i<array.length;i++) {
        let temp=array[i][col1];
        array[i][col1]=array[i][col2];
        array[i][col2]=temp;
    }
    return array;
}

let modifiedArray = switchColumns(arrayData, 2, 3);

console.log(modifiedArray);

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 creating a series using a provided array?

Hello, I am a VB.Net user and looking to transform an array into a series. The array is as follows: Dim QRList() As Integer = {1, 2, 3, 4, 9, 12, 13, 14, 15, 16, 41, 42, 44, 48, 49, 50} The series should look like this: 1 - 4, 9 - 9, 12 - 16, 41 - 42, 44 ...

What options are available for labels in Bootstrap v5.0.0-beta1 compared to BS 3/4?

How can I use labels in Bootstrap v5.0.0-beta1? In Bootstrap 3, the labels are implemented like this: <link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet" /> <span class="label label-success ...

Eliminating the Skewed Appearance of Text in Input Fields Using CSS

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Customized Page Layout</title> <script src="https://c ...

JavaScript on Ruby on Rails stops functioning in js.erb file

I have encountered an issue with pagination using AJAX in a view. Initially, I had two paginations working perfectly fine with their respective AJAX calls. However, when I tried to add a third pagination (following the same method as the previous two), it ...

Handling click events on several elements in Angular

My Objective: I aim to implement a collapsible accordion feature on a webpage that expands and collapses upon clicking. The expansion is triggered by adding the class collapsible-panel--expanded. My Approach: For each item, I have set a click event as fo ...

Cease the execution of promises as soon as one promise is resolved

Using ES6 promises, I have created a function that iterates over an array of links to search for an image and stops once one is found. In the implementation of this function, the promise with the fastest resolution is executed while others continue to run ...

Personalized Owl Carousel - OWL.JS Hover Pause Feature

I have been working on a slider in Codepen that is functioning well, and now I am trying to tweak it for my website. My goal is to make the carousel pause when someone hovers over it. I've experimented with all the options available on the owl slider ...

The outcome of my function designed to calculate the highest possible profit using k transactions is a null array

I have developed a custom function to calculate the maximum profit from a series of stock transactions given a specific number of transactions allowed. Each transaction involves buying at a low price and selling at a higher price, with the rule that you ...

Mobile devices seem to be constantly refreshing website images

I have a landing page consisting of multiple sections with images as the background, each section occupying the full screen. In one specific section, the images change every 5 seconds. The website works smoothly on desktop, but I encounter issues on mobil ...

React displaying incorrect data during array iteration

I have encountered a peculiar problem that I can't seem to find any information about online. If my issue has already been discussed elsewhere, I apologize for the duplicated query. The challenge revolves around managing a "Schedule" represented by a ...

The custom tooltip is not being displayed as intended

I'm currently working on customizing tooltips in angularjs google charts. My goal is to display multiple series data along with some text within the tooltip, similar to the demo showcased here. Specifically, I aim to include the legend and title of th ...

The functionality of ngSubmit and ngDisabled seems to be malfunctioning, although ngModel is successfully linked to the

Despite following the usual process of creating a form in AngularJS, the ngSubmit function is not working as expected and the ngDisabled feature is failing to disable the button when the fields are empty. I even tried isolating the section in a new project ...

Utilizing request parameters within middleware that employs the 'createHandler' function from the 'graphql-http' package

I'm currently working on an Express server that uses GraphQL to handle HTTP requests. One of the key features of this Express server is the implementation of two crucial middlewares: app.use(authenticate); app.use('/graphql', createHandler ...

There is a message showing up on the console log, but unfortunately, it

I'm attempting to save the server error message output to a file, however, despite seeing the message in console.log below, it's not being written to the file and remains empty. Any suggestions on why this might be happening? const fileName = `re ...

Photo uploading in ASP.NET MVC - encountering null HttpPostedFileBase issue

QUESTION: I'm having an issue where the Photo1 value is null in the controller post method despite uploading it. Can someone help with this? This is my model class: class ProductVM{ public string Name { get; set;} public string Color {get; ...

What could be causing the second switchMap to be triggered repeatedly upon subscription?

Check out the code snippet below for reproducing the issue: import { defer, BehaviorSubject, of } from "rxjs"; import { shareReplay, switchMap } from "rxjs/operators"; const oneRandomNumber = defer(() => of(Math.floor(Math.random() ...

React components are failing to display data as expected

I need to display certain data based on the id provided in the url. When I use console.log() with res.json, I can see the data but I'm unsure how to pass it to the 'articleComponent'. const Articles = () => { const query = (id) => ...

Fixed columns with horizontal scrolling to prevent Datatables columns from overlapping

I'm facing an issue with my data table created using datatables. I need to fix the first two columns, but when I do so, the other two columns overlap them while scrolling horizontally. If I remove the fixed columns, the scrolling works correctly witho ...

Troubleshooting UV Mapping Problem in THREEJS JSON Model

After reviewing the json file for a 3D model, I came across the following line: "uvs": [[-3.21834,-1.65399,-3.21834,-2.57657,4.21834,-2.57657,4.21834,-1.65399,4.21834,-1.85233,4.21834,-2.7749,-3.21834,-2.7749,-3.21834,-1.85233,4.21834,0.961286,-3.21834,0 ...

In ASP.Net, looking to execute JavaScript once the update panel finishes loading

Is there a way to trigger a JavaScript function only when the update panel has completely loaded, rather than on the initial page load? I want to be able to scroll once the update panel is fully loaded. If anyone has any suggestions or solutions, please l ...