Arranging elements from one array into another array in Javascript in ascending order

I have a unique collection of arrays with varying lengths. For example, in my test scenario, I initialized my vidArray with 4 arrays (having lengths of 16, 38, 49, and 49 respectively). My goal is to create a newArray that combines the elements from each array in sequence.

This is my approach:

      // populate newArray
      var newArray = []
      for(let i=0; i < vidArray.length; i++){
        let currentArray = vidArray[i]
        for(let j=0; j < currentArray.length; j++){
          newArray.push(currentArray[j])
        }
      }

      console.log("newArray: "+newArray)

However, the output appears incorrect as it seems to mix elements from different arrays inconsistently.

Answer №1

If you want to determine the maximum length of subarrays, simply loop through all arrays and create a new array by including corresponding values from each subarray if they exist:

const vidArray = [
  [1, 2, 3, 4, 5],
  [11, 12, 13, 14],
  [21, 22, 23],
  [31, 32, 33, 34, 35, 36]
];

let newArray = [];
const maxLength = Math.max(...vidArray.map(a => a.length));

for (let i = 0; i < maxLength; i++) {
  vidArray.forEach(a => {
    if (a[i]) newArray.push(a[i]);
  });
}

console.log(newArray);

Answer №2

Check out this interesting approach that leverages a mix of reduce and forEach.

const data = [
  ["apple", "banana", "cherry", "date"],
  ["elderberry", "fig"],
  ["grape", "honeydew", "kiwi", "lemon"],
  ["mango", "nectarine", "orange"]
]

const resultArray = data.reduce((accumulator, innerArray) => {
  innerArray.forEach((element, index) => {
    if (!accumulator[index]) accumulator[index] = [];
    accumulator[index].push(element);
  });
  return accumulator;
}, []);

console.log(resultArray);

// To get the final output as one single array:
console.log(resultArray.flat());

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

Expanding the size of a div using the Bootstrap grid system

I need to customize the width of the date column on my inbox page so that it displays inline without breaking the word. Even when I use white-space: nowrap, the overflow hides it due to the fixed width. I want the name and date classes to be displayed in ...

Have Babel transpile configuration files into CommonJS format

I'm having trouble getting my Nuxt app to work with Jest for testing. I have a setupFilesAfterEnv property set with a setupTests.ts file that imports a translation file. The translations file uses ES6 import/export module syntax, but it seems like my ...

Unable to trigger onclick event for creating a new title

I'm currently working on a text generator project using JavaScript. My goal is to create a function that saves the selected text from a dropdown menu and displays it as the page title when the "Generate" button is clicked. The issue I'm facing i ...

What could be causing these strange white lines to show up on my AFrame meshes?

When I import a GLB scene with baked textures into A-Frame using THREE.js, I am experiencing an issue where white lines appear on my objects (pictured below). The walls are grouped meshes which may explain the lines appearing there, but I am puzzled as to ...

Sending the handleSubmit() function to the child component does not alter the state of the parent component

I just started learning React and Javascript. Currently, I am working on a form where users can specify the details of a "Mob". Upon submitting the form, I anticipate that handleSubmit() (which is passed down from the parent component) will update the sta ...

What is the best way to identify when a cell has been modified in ng-grid aside from just relying on the ng-grid event

My web application features an editable ng-grid that has greatly simplified my work, but I have encountered a minor issue. I need a way to detect when a user makes changes to the grid without having to compare each field before and after. Currently, I am ...

What is the most effective way to ensure that a child component only executes when a link is clicked on the Vue component?

There are two components in my code The first component, which is the parent component, looks like this : <template> <ul class="list-group"> <li v-for="item in invoices" class="list-group-item"> <div class="ro ...

Transmission of state modifications in React

My React project is organized with the following hierarchy: The main A component consists of child components B and C If I trigger a setState function in component B, will components A and C receive notification and potentially re-render during the recon ...

Error in Charts API - [draw function failed to render for one or more participants]

Currently encountering an error on the client side where one or more participants failed to draw. I am able to successfully output data in the drawVisualization call, indicating that the issue lies within the JavaScript code. Despite following examples, I ...

Using a Svelte click event to toggle a boolean value in an array from a div

How can I modify the toggle functionality to work on any click event, not just on a button, in order to trigger a state change regardless of the element clicked? ToolBar.ts export default class ToolBar { options:Array<ToolBarOptions>; const ...

Having trouble with the Bootstrap dropdown not activating the click event?

My issue involves a Bootstrap dropdown where the click event is not triggering. I'm curious about why the click event won't trigger and if there's a solution available to fix this problem. <div class="dropdown d-inline-block"> ...

Why is Visual Studio Code not highlighting my nested multi-line JavaScript comment as I anticipated?

/*/*! what is the reason */ for this annotation*/ Can someone explain why the annotation is not working as expected in this scenario? I've already verified it in VS code. ...

Tips for deleting a duplicate identifier within an li element that possesses a particular class through javascript

I need help removing duplicate IDs from list items with a specific class. For example, in the following list, there are duplicates IDs (small, medium) and I want to remove the IDs with the class "size". How can I achieve this? <ul id="bulk"> ...

Having trouble with popovers after upgrading to bootstrap v4

I am facing an issue while trying to migrate Bootstrap from version 3 to 4. The problem specifically lies with popovers and the popper.js library. Each time I hover over an element, the following error is displayed: Uncaught TypeError: Cannot read property ...

Setting up Stylelint in a Vue 3 app with VSCode to automatically lint on save

I am looking to perform linting on my scss files and scss scope within .vue components. Here is what my configuration looks like in stylelint.config: module.exports = { extends: [ 'stylelint-config-standard', 'stylelint-config-rece ...

Transform an Angular 2 application to seamlessly incorporate an SDK

I have been working on an Angular 2 application and I am curious if it is feasible to transform this into an SDK that can be easily integrated into other applications by simply adding script tags in their headers. If this conversion is not achievable, co ...

Update destination upon click

I'm new to JavaScript and attempting to modify a redirect link using checkboxes that will modify the URL, followed by a button that will use the updated URL. However, I'm facing some challenges with my code and could use some guidance. Here is t ...

Can you explain the meaning of the code provided below?

I'm having trouble understanding the functionality of this code snippet: .bind(this); (I copied it from the Zurb Foundation dropdown plugin) .on('mouseleave.fndtn.dropdown', '[data-dropdown], [data-dropdown-content]', function ( ...

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 ...

mandatory data fields for an HTML form

I'm having some trouble creating an HTML form with mandatory input fields. The code I have so far is shown below: <div class="col-sm-6"> <label for="city" class="form-control">City ...