Traversing through rows of a two-dimensional array that stores arrays of varying lengths

I have developed a function that extracts all elements from a 2D array by rows and converts them into a 1D array. The input array can have varying numbers of columns and rows.

For example:

let arr = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
];

This will return:

[1, 5, 9, 2, 6, 10, 3, 7, 11, 4, 8, 12]

The function I have created is as follows:

convertList = (list) => {
    let result = [];
    let listTotalEntries = R.sum(R.map(R.length)(list));
    let mod = R.modulo(R.__, list.length);

        let counterRow = -1;

        for (let i = 0; i < listTotalEntries; i++) {
            if (mod(i) === 0) {
                counterRow++;
            }
            if (list[mod(i)][counterRow]) {
                result.push(list[mod(i)][counterRow]);
                console.log(list[mod(i)][counterRow]);
            }
        }
        console.log(result);
        return result;
};

Inquiry: Currently, this function only works with square matrices. How can I modify it to handle arrays with varying lengths?

For instance:

let arr = [
    [1, 2],
    [],
    [9, 10, 11, 12]
];

Desired output:

[1, 9, 2, 10, 11, 12]

Thank you for your assistance!

Muff

Answer №1

There was a ramda.js tag included in this content. Utilizing Ramda makes it simple, as there are two functions that come in handy:

const convertList = compose(flatten, transpose);
convertList(arr); //=> [1, 9, 2, 10, 11, 12]

transpose reverses a matrix over its main diagonal, essentially changing rows to columns and vice versa. The flatten function converts a list of lists into a single list. By using compose in this manner, it effectively creates the equivalent of

list => flatten(transpose(list))
.

To witness this process firsthand, visit the Ramda REPL.

Answer №2

My recommendation is to tackle the arrays one step at a time.

var arr1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]],
    arr2 = [[1, 2], [], [9, 10, 11, 12]];

function single(array) {
    var result = [],
        maximum = Math.max.apply(null, array.map(function (a) { return a.length; })),
        index = 0, j,
        length = array.length;

    while (index < maximum) {
        for (j = 0; j < length ; j++) {
            index in array[j] && result.push(array[j][index]);
        }
        index++;
    }
    return result;
}

document.write('<pre>' + JSON.stringify(single(arr1), 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(single(arr2), 0, 4) + '</pre>');

Answer №3

Have you experimented with this straightforward approach?

const singleDimensionArr = arr.reduce((prev, current) => prev.concat(current));

For instance:

[
    [1, 2],
    [],
    [9, 10, 11, 12]
].reduce((prev, current) => prev.concat(current));

will produce [1, 2, 9, 10, 11, 12]

Note:

After receiving feedback from the original poster below, it seems that concatenation needs to occur column-wise.

const max = Math.max(...arr.map(a => a.length));
const finalArr = [];
for (let i = 0; i < max; i++) {
   for (let j = 0; j < arr.length; j++) {
       arr[j][i] ? finalArr.push(arr[j][i]) : "";
   }
}
console.log(finalArr);

Answer №4

This illustration demonstrates the creation of a large sparse array by placing each element in its corresponding position in a square-like arrangement. It then eliminates any null values that may have been generated where no input item exists.

let arr = [
    [1, 2],
    [],
    [9, 10, 11, 12]
];

var output = arr.reduce(function(outputArray, innerArray, index, mainArray) {
  for (var subIndex=0; subIndex<innerArray.length; subIndex++){
    outputArray[mainArray.length * subIndex + index] = innerArray[subIndex];
  }
  return outputArray;
},[]).filter(function(element) {
  return element !== null;
});

alert(JSON.stringify(output));

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

gathering information from various asynchronous functions (promises)

When faced with the need to retrieve data from multiple asynchronous functions or promises, how can you efficiently collect and persist the data so that it can be utilized once all operations are complete? An example scenario would involve executing multip ...

JavaScript Password Form Submission - Enter your password in the form

I need assistance with setting up a password for a form. Users should be able to enter a password into a specified field, click submit, and if the password is correct, they will be redirected to buybutton.php in the same window. If the password is incorr ...

Ways to completely obliterate a datatable?

Currently, I am utilizing datatables in conjunction with bootstrap-daterangepicker to set a range for displaying data in Datatables. Everything is functioning correctly so far. However, the issue arises when I choose a new range in daterangepicker, it of ...

Tips for choosing or unselecting a row within a Table utilizing the Data Grid Mui

Is it possible to implement row selection and deselection in Mui without using the checkboxSelection prop? I am looking for a way to achieve this functionality in @mui/x-data-grid when clicking on a row. Below is the code snippet from the Table Component ...

How can one iterate through elements of a specified length using Jquery?

Currently, I am in the process of designing an animation for my website. The animation involves different divs that each contain an image and a description related to that image within an aside element. The width of the aside is slightly wider than the ima ...

Learn the process of utilizing JavaScript/Node.js to dynamically upload images onto a webpage directly from a database

Currently, I am developing a web application and building a user profile page where I aim to showcase user information along with a profile picture. Working with node/express/jade stack, I have a javascript file that manages loading the appropriate jade vi ...

Error encountered when running the production build server for android in Meteor: TypeError - Unable to access property 'slice' of null

Here's a demo I'm working on: https://github.com/pc-magas/pupAndroidDemo I'm trying to build this demo for Android. I've already installed the Android SDK and configured the necessary environmental parameters. Following the instructio ...

Insert an HTML page into a div element

I am having an issue with my angular template. I have a div where I am attempting to load an HTML view file (.html) based on a $watch event, but for some reason, the HTML view is not being loaded into the div. Below is a snippet of my controller code that ...

"Sorry, but window.print function is not available in this environment

Whenever I try to execute something in jest, I keep encountering the same error message: console.error node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29 Error: Not implemented: window.alert at module.expor ...

What is the necessity of utilizing getStaticPaths() alongside getStaticProps()?

When working with dynamic routes, such as [id].js, the static pages generated using npm run build will result in an [id].html page. Any route containing /something will display "Hello World". However, when we dynamically generate content on the page by ut ...

Steps to include a personalized function in a Mongoose Model

One way to extend Mongoose is by adding methods to documents. Here's an example: const userSchema = new mongoose.Schema({ balance: Number }) userSchema.methods.withdrawBalance = function(amount){ const doc = this doc.balance = doc.balance - amou ...

Is there a way to retrieve the form name within my directive?

In my code, I am able to retrieve the ngModel name, but now I am looking for a way to also capture the form's name that contains the element with the "validacion" directive. It is crucial for me to programmatically obtain the form's name where t ...

Developing NodeJS applications locally using Docker

How can I effectively develop an app locally within a container with access to my laptop's file system for the node_modules? Currently, my Dockerfile includes the following settings: COPY package.json /app/ RUN npm install COPY . /app/ And my docke ...

Multiplication cannot be performed on operands of type 'NoneType'

Hello everyone, I am attempting to calculate the unit price and quantity from this table using the following model: class Marketers(models.Model): category =models.ForeignKey(Category, on_delete=models.CASCADE, null=True) name =models.CharField(max ...

Guide on implementing toastr.js in an Angular 4 component

I'm attempting to incorporate toastr.js into my Angular component by referencing toastr.js located in ../../../../../scripts/thirdparty/toastr.js however, when I try to import it like this import * as toastr from 'toastr'; even after ins ...

Javascript SQL query not returning the expected multiple rows, only returning one instead

I have a table containing multiple rows of test results, each row includes the ID of the test taker. Using the logged-in user information, I've added additional rows to the table to ensure accuracy. However, when printing the result to the console, on ...

Continuously encountering IndexErrors while attempting to manipulate char arrays

Currently in the midst of a simulation project, I have a piece of code that organizes data into an array in a particular way: [['_' '_' 'F' '_' '_'] ['_' '_' '_' '_&apos ...

Prevented a frame from "https://googleads.g.doubleclick.net" from accessing another frame

After placing ads on my website, they are displaying properly. However, I am receiving an error repeatedly in the console when the page loads: A frame from origin "" is being blocked from accessing a frame with origin "". The requesting frame has an "ht ...

javascript The mouseout event is triggered on an interactive iframe

Whilst navigating the controls within a virtual tour iframe, I've noticed that the jQuery mouseout event sometimes triggers. This can be quite frustrating as I have a separate function in place for the mouseout event specifically related to the iframe ...

Creating a JavaScript interface for an XML API generated by Rails?

Working with a large Ruby on Rails website has been made easier thanks to the REST support in Rails 2. The site's business logic can now be accessed through a consistent XML API. My goal now is to create one or more JavaScript frontends that can inter ...