Traversing the nested arrays, processing column by column

Below is an array of subarrays

const array = [
[0, 1, 2, 3],             // Going from top to bottom?
[4, 5, 6, 7, 8, 9],       // |
[10, 11, 12, 13, 14],     // |
[15, 16, 17, 18, 19],     // |
]                         // V

My goal is to achieve the following output

newArray = [0, 4, 10, 15, 1, 5, 11, 16, 2, 6, 12 ...] 

This is my current approach:

      let idx = 0;
      let newArray = []
      for (let i = 0; i < array.length; i++) {
        for (let j = 0; j < array[i].length; j++) {
          newArray.push(array[idx][j])
          idx++;
        }
        idx = 0;
      }

Answer №1

Here is a potential solution:

const array = [
  [0, 1, 2, 3],             // Traverse from top to bottom?
  [4, 5, 6, 7, 8, 9],       // |
  [10, 11, 12, 13, 14],     // |
  [15, 16, 17, 18, 19],     // |
]
// check if there is "more" to read
let hasMore = true;
// result array
const res = [];
// index for each "column"
let el = 0;
while(hasMore){
  // assume no more elements to read initially
  hasMore = false;
  // iterate through all elements in the input array
  for(let i = 0; i < array.length; i++){ 
    // check if the el-th element exists
    if(array[i][el] != undefined){
      // set flag that there might be more to read (i.e., next column)
      hasMore = true;
      // add the element to result
      res.push(array[i][el])
    }
  }
  // move to the next column
  el++;
}
console.log(res);

Alternatively, a functional style solution could be:

const array = [
  [0, 1, 2, 3],             // Traverse from top to bottom?
  [4, 5, 6, 7, 8, 9],       // |
  [10, 11, 12, 13, 14],     // |
  [15, 16, 17, 18, 19],     // |
]
const res = array.flatMap(
  el => el.map(
    (o, i) => ({
      index: i,
      el: o
    })
  ))
  .sort((a, b) => a.index - b.index)
  .map(({el}) => el)

console.log(res)

Answer №2

Uncertain if this method will solve the problem since it involves creating a new array, but it could be beneficial.

let freshArray = Array.prototype.concat.apply([], originalArray);

Answer №3

Here's a different example demonstrating the use of various methods:

const array = [
  [0, 1, 2, 3],
  [4, 5, 6, 7, 8, 9],
  [10, 11, 12, 13, 14],
  [15, 16, 17, 18, 19],
]

var final = Object.values(
  array.reduce((acc, cur) => (
    cur.map((elm, idx) => idx in acc ? acc[idx].push(elm) : acc[idx] = [elm]), acc
  ), {})
).flat();

const pre = document.createElement('pre');
pre.innerText = JSON.stringify(final);
document.querySelector('body').appendChild(pre);

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 best way to calculate the total number of results using ajax?

Encountering an issue with the total count of ajax search results. Getting an error message "Method Illuminate\Database\Eloquent\Collection::total does not exist." when using directives, for example: <div class="searched-item"&g ...

Using a carousel component in Bootstrap

Just starting out with this, trying to customize Bootstrap to change slides automatically. I followed the documentation at https://getbootstrap.com/docs/4.3/components/carousel/ but for some reason, the slides aren't changing on an interval, even thou ...

Elevating the Components of an Array Similar to a Numeric Value

Currently, I am in the process of developing a Sudoku-solving program. In order to determine the solution for the puzzle, my program interprets 0s as vacant slots and generates an array that matches the total number of zeros present in the Sudoku puzzle. S ...

using absolute URLs for image source in JavaScript

How can I output the absolute URLs of images in a browser window (e.g., 'www.mysite.com/hello/mypic.jpg')? Below is a snippet of my code: $('img').each(function() { var pageInfo = {}; var img_src = $(this).attr('s ...

The Power of AngularJS - Unlocking the Potential of Module Configuration

Exploring the concepts in this AngularJS example: angular.module('myModule', [], function($provide) { $provide.factory('serviceId', function() { var shinyNewServiceInstance; //the factory function creates shinyNewServiceInsta ...

The mystery of the unassigned value in $(this).data(value) when using the jQuery click() method

In my Rails 5 application, I am working on creating a dynamic menu that will guide users to different parts of the site based on their location. The idea is that when they click on a specific menu item from the home page, a modal will appear allowing them ...

What could be causing my data to shift after refreshing in Firefox with the F5 key?

My webpage has four tables, each containing rows with two text boxes filled with numeric values from the server. However, something peculiar occurs. When I add data to a row, let's say row 1, and then refresh the page, two values are mysteriously mov ...

The jQuery .click() function is not triggering when clicked

$("#backButton-1").click(function() { $("#form-2").empty(); $("#form-1").show(); }); I am experiencing trouble with this code snippet. The form-1 element is hidden, and the backButton-1 is created after the end of for ...

Stop the reloading of the parent page when the exit button is pressed on the popup screen

I have set up a modal popup that appears when a user clicks on a specific link. Inside the popup, I have included an exit button to close it. However, I am facing an issue where clicking on the exit button not only closes the popup but also reloads the par ...

Dynamic class/interface in Typescript (using Angular)

Is there a way to achieve intellisense for an object created with a dynamic class by passing parameters? Here is the code snippet: Main: let ita: any = new DynamicClass('ITA'); let deu: any = new DynamicClass('DEU'); The DynamicClass ...

"Upon loading the page, I encounter JavaScript errors related to Angular's ngOnInit function. However, despite these errors,

I have a page in angular where I am loading data in the ngOnInit function. The data loads correctly and is displayed on the page, everything seems to be working fine. However, I am encountering numerous javascript errors in the console stating cannot read ...

Error in AJAX transmission

I am encountering an unusual issue with the jQuery ajax function in my script. The problem is specific to my friend's computer, as I am not experiencing any difficulties on my own computer. While attempting to utilize the error function property to ...

It's next to impossible to secure expedited work on an ongoing project using Vercel

Yesterday, I successfully deployed an application on Vercel using only ReactJS. Today, I made the decision to develop an API for my application, To clarify, I have a folder housing the React app, and within that, I created a directory named "api" followi ...

Utilizing cookies to track the read status of articles - markers for reference

Currently, I am in the process of developing a website and am interested in implementing a feature that allows users to track which articles they have read. I am considering adding a small circle next to each article heading to signify whether it has been ...

Dynamic AJAX Dependent Dropdown Menu

Can you help me create a dynamic input form? I need assistance in creating an input form with a dynamic dropdown list, similar to the screenshot provided below: https://i.stack.imgur.com/rFSqV.png What is my current script setup? The script I have is d ...

A guide to removing functions from the render method

Greetings! Currently, I am in the process of creating a simple webpage that utilizes a map function to display all details to the user. Some fellow developers have advised me to remove my functions from the render method, as it continuously renders unneces ...

Having trouble sending an ajax request from localhost to a remote server

When attempting to make an ajax request (using jquery) from my local server to a remote page where I am the administrator, I encounter the following error: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin &ap ...

Try enabling automatic status bar filling in Onsen UI when working with AngularJS

Completely new to AngularJS, I am trying to understand how to use ons.enableAutoStatusBarFill(); in order to prevent my menus from overlapping the status bar. This is how I have set up my controller: var mod = ons.bootstrap('app', ['onsen& ...

Ways to customize the border color on a Card component using React Material UI

Is there a way to change the border color of a Card component in React Material UI? I attempted using the style property with borderColor: "red" but it did not work. Any suggestions on how to achieve this? ...

Resolving the bothersome complications of self-looping steps in jQuery animate delay

My timeline definition includes selectors and a sequence of delays and animations to apply to an object. I have also provided the option to loop through the steps for a specific object. Here is the function that I use to queue the animations: function an ...