• 0

JS Array Mix


Question

If I had 2 arrays that looked like this:

 

["1", "2", "3", "4", "5"]

and

["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"]

 

and I wanted to make it end up like this:

["A", "1", "B", "2", "C", "3", "C", "4", "E", "5", "F", "G", "H", "I", "J", "K"]

 

What would be the easiest way to do it in JS, especially assuming that we may never know the length of the first two arrays?  It should also allow duplicates.

 

Thank you.

Link to comment
https://www.neowin.net/forum/topic/1422426-js-array-mix/
Share on other sites

7 answers to this question

Recommended Posts

  • 0

I've found the solution:

 

var arr1 = ["1", "2", "3", "4", "5"],
    arr2 = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"],
    arr3 = [],
    arrLen = Math.min(arr1.length, arr2.length);
    
for (i = 0; i < arrLen; i++) {
    result.push(arr1[i], arr2[i]);
}

arr3.push(...arr1.slice(arrLen), ...arr2.slice(arrLen));
console.log(arr3);

 

  • Like 1
Link to comment
https://www.neowin.net/forum/topic/1422426-js-array-mix/#findComment-598769185
Share on other sites

  • 0

Your code seems way too complicated for no reason. Here's a better solution if you don't mind modifying the source arrays

 

let array1 = ["1", "2", "3", "4", "5"];
let array2 = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"];
let array3 = [];

while (array1.length > 0 || array2.length > 0)
{

	if (array1.length > 0)  array3.push(array1.shift())
	if (array2.length > 0)  array3.push(array2.shift())

}

 

 

Edited by PmRd
  • Like 1
  • Thanks 1
Link to comment
https://www.neowin.net/forum/topic/1422426-js-array-mix/#findComment-598769186
Share on other sites

  • 0
  On 16/10/2022 at 03:23, PmRd said:

Your code doesn't work and seems way too complicated for no reason. Here's a better solution if you don't mind modifying the source arrays

 

let array1 = ["1", "2", "3", "4", "5"];
let array2 = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"];
let array3 = [];

while (array1.length > 0 || array2.length > 0)
{

	if (array1.length > 0)  array3.push(array1.shift())
	if (array2.length > 0)  array3.push(array2.shift())

}

 

 

Expand  

Thank you. Your method is much more elegant

  • Like 2
Link to comment
https://www.neowin.net/forum/topic/1422426-js-array-mix/#findComment-598769189
Share on other sites

  • 0
  On 16/10/2022 at 03:30, Brian Miller said:

Thank you. Your method is much more elegant

Expand  

If you want the source arrays to remain intact you can do this instead

 

let array1 = ["1", "2", "3", "4", "5"];
let array2 = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"];

function mix(arr1, arr2) {
  
    let array1clone = [...arr1];
    let array2clone = [...arr2];
  
    let result = [];
  
    while (array1clone.length > 0 || array2clone.length > 0)
    {

      if (array1clone.length > 0)  result.push(array1clone.shift())
      if (array2clone.length > 0)  result.push(array2clone.shift())

    }
  
    return result;
  
}

console.log(mix(array1, array2));

 

  • Like 1
Link to comment
https://www.neowin.net/forum/topic/1422426-js-array-mix/#findComment-598769190
Share on other sites

  • 0
  On 16/10/2022 at 03:35, PmRd said:

If you want the source arrays to remain intact you can do this instead

 

let array1 = ["1", "2", "3", "4", "5"];
let array2 = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"];

function mix(arr1, arr2) {
  
    let array1clone = [...arr1];
    let array2clone = [...arr2];
  
    let result = [];
  
    while (array1clone.length > 0 || array2clone.length > 0)
    {

      if (array1clone.length > 0)  result.push(array1clone.shift())
      if (array2clone.length > 0)  result.push(array2clone.shift())

    }
  
    return result;
  
}

console.log(mix(array1, array2));

 

Expand  

I like that. Thank you

Link to comment
https://www.neowin.net/forum/topic/1422426-js-array-mix/#findComment-598769191
Share on other sites

  • 0

Here's a fancy-pants version that supports an arbitrary number of arrays and also sparse arrays:

 

function mixArrays(...arrays) {

    const arrayLengths = arrays.map(array => array.length);
    const maxLength = Math.max(...arrayLengths);
    
    let result = [];

    for (let index = 0; index < maxLength; index++) {
        for (let array of arrays) {
            if (index in array) {
                result.push(array[index]);
            }
        }       
    }

    return result;
}

 

Example with two arrays:

 

let array1 = ["1", "2", "3", "4", "5"];
let array2 = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"];
let array3 = ["a", "b", "c"];

mixArrays(array1, array2);
// ['1', 'A', '2', 'B', '3', 'C', '4', 'D', '5', 'E', 'F', 'G', 'H', 'I', 'J', 'K']

 

Three arrays:

 

mixArrays(array1, array2, array3);
// ['1', 'A', 'a', '2', 'B', 'b', '3', 'C', 'c', '4', 'D', '5', 'E', 'F', 'G', 'H', 'I', 'J', 'K']

 

And sparse arrays:

 

array1[8] = "8";

mixArrays(array1, array2);
// ['1', 'A', '2', 'B', '3', 'C', '4', 'D', '5', 'E', 'F', 'G', 'H', '8', 'I', 'J', 'K']

 

  • Like 1
Link to comment
https://www.neowin.net/forum/topic/1422426-js-array-mix/#findComment-598769244
Share on other sites

  • 0
  On 16/10/2022 at 12:39, DonC said:

Here's a fancy-pants version that supports an arbitrary number of arrays and also sparse arrays:

 

function mixArrays(...arrays) {

    const arrayLengths = arrays.map(array => array.length);
    const maxLength = Math.max(...arrayLengths);
    
    let result = [];

    for (let index = 0; index < maxLength; index++) {
        for (let array of arrays) {
            if (index in array) {
                result.push(array[index]);
            }
        }       
    }

    return result;
}

 

Example with two arrays:

 

let array1 = ["1", "2", "3", "4", "5"];
let array2 = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"];
let array3 = ["a", "b", "c"];

mixArrays(array1, array2);
// ['1', 'A', '2', 'B', '3', 'C', '4', 'D', '5', 'E', 'F', 'G', 'H', 'I', 'J', 'K']

 

Three arrays:

 

mixArrays(array1, array2, array3);
// ['1', 'A', 'a', '2', 'B', 'b', '3', 'C', 'c', '4', 'D', '5', 'E', 'F', 'G', 'H', 'I', 'J', 'K']

 

And sparse arrays:

 

array1[8] = "8";

mixArrays(array1, array2);
// ['1', 'A', '2', 'B', '3', 'C', '4', 'D', '5', 'E', 'F', 'G', 'H', '8', 'I', 'J', 'K']

 

Expand  

Thank you, that is totally fancy pants!!! :D

 

Link to comment
https://www.neowin.net/forum/topic/1422426-js-array-mix/#findComment-598769384
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • The one thing people should pirate is the operating system. You can't get rid of it...
    • "prepare for mandatory Windows 11 upgrade" This is apparently some new use of the word "mandatory" with which until now I was not acquainted. What's the consequence for non-compliance? Microsoft whining incessantly at you? Trump will levy a tariff on you? Oh wait, that's what they're doing now.
    • Waste of money. Most of Africa is a 14th century sewer. South Africa use to be wealthy & doing well until they "kicked out" the ones running it.
    • Adobe releases all-new Photoshop app for Android devices by Pradeep Viswanathan Early this year, Adobe released an all-new Photoshop app for iOS devices. Designed from the ground up for smartphones, the app allows users to easily add, remove, adjust, and combine content, as well as access free Adobe Stock assets to create new visuals. Today, Adobe announced a similar, brand-new Photoshop app for Android devices, currently in beta. It’s important to note that this Android version is not intended to replace the desktop version of Photoshop. Instead, it offers access to select powerful Photoshop features—including layering, masking, and the new Generative Fill—within an easy-to-use mobile interface. During the beta phase, the following features are available to all users: Following the beta phase, users will need a new Photoshop Mobile & Web plan to access the premium features. The premium features list includes the ability to remove objects by brushing over them with the Remove Tool, the ability to use Clone Stamp to hide unwanted objects by cloning areas of an image, the ability to fill portions of an image with content sampled from other parts of the image with Content-Aware Fill, the ability to export using additional file formats (PSD, TIF, JPG, PNG), and more. You can download the Adobe Photoshop app from the Google Play Store if your device is running Android 11 or later and has at least 6GB of RAM (8GB or more is recommended for optimal performance).
    • And what about all the toxic waste that "clean" nuclear energy produces?
  • Recent Achievements

    • Conversation Starter
      DarkShrunken earned a badge
      Conversation Starter
    • One Month Later
      jrromero17 earned a badge
      One Month Later
    • Week One Done
      jrromero17 earned a badge
      Week One Done
    • Conversation Starter
      johnwin1 earned a badge
      Conversation Starter
    • One Month Later
      Marwin earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      245
    2. 2
      snowy owl
      156
    3. 3
      ATLien_0
      142
    4. 4
      +FloatingFatMan
      138
    5. 5
      Xenon
      129
  • Tell a friend

    Love Neowin? Tell a friend!