Create a new one-dimensional array by stacking the columns of a matrix

In my current project, I am dealing with a complex array of arrays where each inner array contains objects.

My goal is to transform this multidimensional array into a flat array organized in a column-wise order. Here is the code snippet that I have implemented so far:

const newArray = [];

arr.map((rows, i) => {
  rows.map((row) => {
     newArray.splice(i, 0, row);
    });
  });

However, as I progress further into the operation, the order starts getting jumbled up.

(Please note that I am using a Promise library within Node, so the maps should be treated as normal maps)

Current Array Structure

const arr = [
  [
    { Mapped_Index: 'Alignment', item_1: '-' },
    { Mapped_Index: 'Alignment', item_2: '-', item_3: '-' },
    { Mapped_Index: 'Alignment', item_4: '-', item_5: '-' },
    { Mapped_Index: 'Alignment', item_6: '-', item_7: '-' }
  ],
  [
    { Mapped_Index: 'Autonomy', item_1: '-' },
    { Mapped_Index: 'Autonomy', item_2: '-', item_3: '-' },
    { Mapped_Index: 'Autonomy', item_4: '-', item_5: '-' },
    { Mapped_Index: 'Autonomy', item_6: '-', item_7: '-' }
  ],
  [
    { Mapped_Index: 'Belonging', item_1: '-' },
    { Mapped_Index: 'Belonging', item_2: '-', item_3: '-' },
    { Mapped_Index: 'Belonging', item_4: '-', item_5: '-' },
    { Mapped_Index: 'Belonging', item_6: '-', item_7: '-' }
  ]
]

Desired Flattened Array

const arr = [
    { Mapped_Index: 'Alignment', item_1: '-' },
    { Mapped_Index: 'Autonomy', item_1: '-' },
    { Mapped_Index: 'Belonging', item_1: '-' },
   
    { Mapped_Index: 'Alignment', item_2: '-', item_3: '-' },
    { Mapped_Index: 'Autonomy', item_2: '-', item_3: '-' },
    { Mapped_Index: 'Belonging', item_2: '-', item_3: '-' },
   
    { Mapped_Index: 'Alignment', item_4: '-', item_5: '-' },
    { Mapped_Index: 'Autonomy', item_4: '-', item_5: '-' },
    { Mapped_Index: 'Belonging', item_4: '-', item_5: '-' },
  
    { Mapped_Index: 'Alignment', item_6: '-', item_7: '-' },
    { Mapped_Index: 'Autonomy', item_6: '-', item_7: '-' },
    { Mapped_Index: 'Belonging', item_6: '-', item_7: '-' }
]

Answer №1

So, it seems like you're interested in taking the original matrix and transposing it before flattening it:

const result = inputArray[0].flatMap((_, index) => inputArray.map(row => row[index]));

Answer №2

To start, the initial task is to combine an array that contains arrays of objects into a single array of objects:

var merged = [].concat.apply([], arr);

Next, it's important to arrange the objects in order based on their Mapped_Index property:

function compare( a, b ) {
    if ( a.Mapped_Index < b.Mapped_Index ){
        return -1;
    }
    if ( a.Mapped_Index > b.Mapped_Index ){
        return 1;
    }
    return 0;
}

merged.sort(compare);

The third and final step involves sorting by the field names, which can be a bit challenging.

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

Utilizing DOMStringMap data to populate CSS URLs

I am attempting to create a universal CSS modification for a webpage element that resembles: <button data-action="link" class="cardImageContainer coveredImage cardContent itemAction lazy lazy-image-fadein-fast" data-blurhash="lo ...

Node.JS - Struggling to successfully export environment variables between scripts in package.json

Currently, I am working on a Node.JS project using Express and I am facing an issue while setting up environment variables to differentiate between development and production environments. I have created a shell script file containing some environment vari ...

Error: React cannot render objects as children

I am encountering an error that I cannot seem to figure out. The issue seems to be with the following line of code: <p className="bold blue padding-left-30">{question}</p> Specifically, it does not like the usage of {question} in the above pa ...

The npm package installation process encountered difficulties in accessing the Chart.Js library

Currently, I am in the process of developing a web application that tracks and logs hours spent on various skills or activities. The data is then presented to the user through a bar graph created using Chart.js. Initially, I was able to display a mock grap ...

Struggling with updating a user in MongoDB using findOneAndUpdate and encountering a frustrating internal server error 500?

Presently, I am in the process of developing an API that is designed to update the current user in mongoDB based on the data provided in the request. However, whenever I execute findOneAndUpdate(), I encounter a 500 internal server error. (I will outline ...

What drawbacks come with developing an Express.js application using TypeScript?

Curious about the potential drawbacks of using TypeScript to write Express.js applications or APIs instead of JavaScript. ...

Mastering linear regression calculations using vue.js and chart.js

Take for instance, with the current dataset, I am looking to showcase a linear regression I managed to do this in Vista and now I need guidance on how to proceed with the calculation. I am not too familiar with using the formula Here is my HTML: <canva ...

Determine whether a div that has been generated automatically has been selected by the user

My JSON file contains a list of elements, each creating a container. See the code below: $.getJSON('/data/risks.json', function(data) { var html = ''; $.each(data.risk, function(key, value){ html += '<div class="elementlis ...

Click outside of this popup to dismiss it

I have been struggling to figure out how to make this popup close when clicking outside of it. Currently, it only closes when clicked directly on it. Your assistance in this matter is greatly appreciated. Here is the HTML code: <h2>Popup</h2> ...

Steps to resolve the "cannot get product" error on Heroku after submitting a value

view the image description hereI have been working on a MERN full stack project and everything was functioning correctly in my local environment. However, upon deploying it to Heroku, I encountered an error which is displayed below. All other APIs are fu ...

Ways to conceal the scroll bar upon the initial loading of a webpage

Recently, I created a single-page website consisting of 4 sections. The client has specific requirements that need to be fulfilled: The scrollbar should not be visible when the page loads. Once the user starts scrolling past the second section, the scrol ...

Angular 2 Mouseover Functionality

Can anyone share the correct method for creating a hover-like event in the latest Angular2 framework? In the previous Angular1 version, we used ng-Mouseover for this purpose, but it seems like it is no longer available in Angular2. I have searched throug ...

Failure to give an error message occurred during a POST request on Parse.com and ExpressJS platform

I'm facing an issue where a POST request I send fails with error code 500 and there is nothing showing up in my server side error log. It seems like the cloud method may be missing. What's interesting is that the same POST request works fine wit ...

Is there a way to modify the text within a "span" element that directly follows an "i" element using jQuery?

I am attempting to modify the text displayed on a button within a plugin by using jQuery. Here is the outer HTML: <button value="[[3,1,1488182400]]" data-group="2017-02-27" class="ab-hour"> <span class="ladda-label"> <i class="ab-hour ...

"Using ng-include with ng-show doesn't seem to be functioning properly

I am facing an issue with my Angular app where the template is getting too large. I would like to split it and utilize the ng-include directive, but I am struggling to get it to work properly. current state of template.html <div class="edit-ob ...

Displaying iframes in AngularJS using a service

I am currently developing an Angular app and encountering some difficulties with rendering a Soundcloud embed iframe in my HTML. The issue arises when I try to display the tracks stored in the array generated by my getTracks function. Despite successfully ...

Retrieving Records within a Specific Date Range for Check-ins and Check-outs

Our team is currently working on developing booking software that requires handling different room pricing based on specific dates. Each room has distinct pricing for weekdays and weekends. ROOM 1 Pricing 1: September 1st - November 3rd, Weekday: $100, W ...

Pattern matching using regex can also be used to restrict the number of characters allowed

Having some trouble with regex to match a specific pattern and also limit the number of characters: Let's say I have allowed number prefixes: 2, 31, 32, 35, 37, 38, 39, 41, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60 I only want numb ...

sending object value to directive rather than other data variables

I have been attempting to customize the functionality of this functioning http://jsfiddle.net/markcoleman/JNqqU/. In the current fiddle, the object is directly assigned where I am trying to change it to $scope.obj.items. However, passing the object to the ...

initiating an event when the page is loaded

Uncertain if this could be considered an anti-pattern, I am hoping someone can provide insight on a better approach. I have attached a resize event to the window and also want the same code to execute on load. Is this the proper way to achieve this? angu ...