Using JavaScript, combine two arrays of varying lengths in an alternating fashion

Seeking a method to alternate between joining two arrays of different lengths.

const array1 = ['a', 'b', 'c', 'd'];
const array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const result = array1.reduce((arr, v, i) => arr.concat(v, array2[i]), []);

Upon running this code, the output is ['a', 1, 'b', 2, 'c', 3, 'd', 4]

I am aiming for

['a', 1, 'b', 2, 'c', 3, 'd', 4, 5, 6, 7, 8, 9]

const array1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const array2 = [1, 2, 3, 4];
const result = array1.reduce((arr, v, i) => arr.concat(v, array2[i]), []);

When executing this code, we get

['a', 1, 'b', 2, 'c', 3, 'd', 4,'e',undefined,'f',undefined,'g',undefined]

My intended outcome is

['a', 1, 'b', 2, 'c', 3, 'd', 4, 'e', 'f', 'g']

There are two scenarios present here:

If array 1 is shorter, certain values from array 2 will be missing.

In case array 1 is longer, undefined elements will be inserted in between the merged arrays.

Looking for a solution to merge two arrays alternately regardless of their lengths.

While dealing with Swift, simply using zip2sequence provides an easy fix. Is there something similar in JavaScript?

Answer №1

It is advisable to utilize a for loop instead of reduce, as it allows you to avoid being restricted by the length of either array.

const array1 = ['a', 'b', 'c', 'd'];
const array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const len = Math.max(array1.length, array2.length);
const result = [];
for (let i = 0; i < len; i++) {
  if (array1[i] !== undefined) {
    result.push(array1[i]);
  }
  if (array2[i] !== undefined) {
    result.push(array2[i]);
  }
}
console.log(result);

Answer №2

Utilizing Recursion for a Creative Solution

function mergeArrays(arr1, arr2) {
  const interleavedArray = ([x, ...xs], ys) => 
    x ? [x, ...interleavedArray(ys, xs)] : ys;
  
  console.log(interleavedArray(arr1, arr2));
}

const array1 = ['apple', 'banana', 'cherry', 'date'];
const array2 = ['orange', 'pear', 'grape', 'kiwi', 'mango'];

mergeArrays(array1, array2);
mergeArrays(array2, array1);

Answer №3

To tackle this issue, you can also utilize the Array.reduce method by determining which array is longer initially:

const array1 = ['a', 'b', 'c', 'd'];
const array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];

let merge = (a,b) => {
  let short, long
  a.length > b.length ? (long=a, short=b) : (long=b, short=a)
  return long.reduce((r,c,i) => {
    short[i] ? r.push(short[i]) : 0
    return r.push(c) && r
  }, [])
}

console.log(merge(array1,array2))
console.log(merge(array2,array1))

A more concise solution using only Array.forEach would be:

const array1 = ['a', 'b', 'c', 'd'];
const array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];

let merge = (a,b) => {
  let short, long, r=[]
  a.length > b.length ? (long=a, short=b) : (long=b, short=a)
  long.forEach((x,i) => short[i] ? r.push(short[i], x) : r.push(x))
  return r
}

console.log(merge(array1,array2))
console.log(merge(array2,array1))

If you opt to use lodash, the code would resemble something like this:

const array1 = ['a', 'b', 'c', 'd'];
const array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];

let merge = (a,b) => _.compact(_.flatten(_.zip(a,b)))

console.log(merge(array1,array2))
console.log(merge(array2,array1))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

This approach involves using _.zip, _.flatten, and _.compact

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

The C# [WebMethod] will not trigger if the Content-Type "application/Json" is missing

After creating a C# WebMethod, I was able to successfully call it using Ajax, angular, and Postman when adding the header Content-Type: 'application/Json'. Here is an example of the HTTP request that worked: $http({ url: 'default.aspx/G ...

JavaScript - Asynchronous JavaScript and XML

function sendRequest(settings) { settings = { type: settings.type || "POST", url: settings.url || "", timeout: settings.timeout || 5000, onComplete: settings.onComplete || function(){}, onError: settings.onError || function(){}, onSuccess: set ...

The OnClick function seems to be unresponsive, however, there are no error messages displaying in

Currently delving into React to enhance my skills, I decided to craft a joke generator. After establishing a local file and successfully fetching the data (jokes) to showcase on the browser, my current goal is to implement a button that, when clicked, will ...

ng-if directive does not show data in AngularJS

I have a dynamic collection of images and videos that I want to display one at a time. Specifically, when I click on an image ID, I want it to show the corresponding image, and when I click on a video ID, I want it to show the relevant video. Below is the ...

plan for grid-based data representation

I have a dataset structure that needs to be stored in a table as a 2D array with details of the data: Languages|Reading|Writing|Listening English | Good | Excellent | Very good French | Excellent | Good | Fair Persian | Good ...

Activate JavaScript validation

Within each section (displayed as tabs), I have a custom validator. When one tab is active, the other is hidden. To proceed to submission, I need to disable client validation for the inactive tab. I attempt to do this by calling ValidatorEnable(, false); ...

Node.js Middleware Design Pattern: Connectivity Approach

I am embarking on a journey to learn Javascript, Node.js, Connect, and Express as part of my exploration into modern web development stacks. With a background in low-level networking, diving into Node.js' net and http modules was a smooth process for ...

Analyzing the pixel coordinates in a randomly generated array for processing

In a series of 7 columns, I have drawn random ellipses in rows. However, I want to ensure that each ellipse in column one touches the next ellipse in column two, and so on, creating a bar graph effect without any gaps between positions. The end result shou ...

Tips for utilizing $scope in an AngularJS service

Currently, I am storing my API response in a $scope variable within my main controller. However, I realize that rewriting this code in each controller is slowing down my application. I am considering moving it to a service file and using it across all cont ...

Retrieve information from Django and pass it to the Vue template

I'm attempting to transfer information from Django into Vue template variables. views.py def index(request): myvar = 1 return render(request, 'index.html',{'myvar':myvar}) within index.html <span> {{ myvar }} </span& ...

Unable to insert form and view upon file upload click

After attempting a file upload within a form, I noticed that upon submission the data is not being inserted into the database as expected. Additionally, when trying to access the table on another page and clicking on a specific file, the redirection does n ...

What is the most effective method for appending elements to an array using a Svelte store subscription?

I want to store objects in an array in a component every time a subscribed store is updated with data from a WebSocket. My goal is to display the last N data points I have received (N=1000 for instance). The store is defined in socket.js: import { readabl ...

The size of table cells unexpectedly shifts following a click event

As I construct a table dynamically using JS, I encounter an issue where clicking on the btn_dropdown0 button causes it to shift slightly to the left and right. This anomaly occurs because the two empty th elements are resizing when the tbody is toggled to ...

Troubleshooting React hooks: Child component dispatches not triggering updates in parent component

I've been trying to implement a method of passing down a reducer to child components using useContext. However, I encountered an issue where dispatching from a child component did not trigger a re-render in the parent component. Although the state ap ...

Utilize jQuery to run a script once everything is prepared and loaded

My website utilizes ajax technology, and within the ajax page, there is a piece of javascript code that needs to run only after the entire ajax page has loaded. I have attempted to use the following: $( '#ajaxdiv' ).load(function() { } However ...

What could be causing my Vuex state to remain unchanged even after the nuxtServerInit commit?

Although I've been utilizing the nuxtServerInit method to retrieve data from my Contentful CMS and commit the mutation to update the categories state object, I keep encountering an issue where categories remain empty even after attempting to display t ...

What is the purpose of calling Array.prototype.slice on an array with 0 as the starting index?

While exploring the inner workings of Sizzle, I stumbled upon this particular line of code: array = Array.prototype.slice.call( array, 0 ); Upon researching the function, it seems like all it does is return every element in the array starting from index ...

Incompatibility issue between metadata versions for Angular 4 and @ng-bootstrap libraries

I've been working with the Angular bootstrap module and encountered an issue. After installing the module using the command npm install --save @ng-bootstrap/ng-bootstrap and importing it into the main app module, I attempted to re-run the application ...

Listening to events in controllers to update the view in AngularJS

Within my application, I retrieve a list of objects from the server. These objects are then displayed on a left sidebar as a list and on a map (leaflet) as markers on the same page. The markers/map are rendered through a service, while the sidebar list is ...

Adding a condition prior to inserting rows into a table using jQuery

Seeking advice on implementing an HTML template that includes a table and an add button. When the add button is clicked, selections are meant to be added to the table. The requirement is to introduce a condition where if one of the selections contains "Map ...