• 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

    • I agree, if Intel wants to make those 50% margins, they really should stick to sockets longer, someone is more likely to upgrade their CPU when they don't need to purchase a motherboard, then looking at maybe RAM, might as well buy a whole new PC at that point, then before you know they've talked themselves out of the whole thing.
    • not sure why people care about the developers so much. let them do whatever they want. if it succeeds, it can benefit us. if it doesn't, then who cares, your life will go on. i'm glad there are still people who do things without thinking whether the output will be productive to society...
    • this man really knows how to embarass americans! i thought he was platforming on "bringing back respect to america!". really sad to see the grip he has over working class americans. he could (and i might argue already has) spit on the working class and half would kiss his shoe. at least this you gotta give him credit for. who else can do this with applause and cheer.
    • Get this 27-inch ASUS VA279QG 120Hz monitor for dirt-cheap by Taras Buria If you are on a very tight budget but you still want to upgrade your monitor to something more exciting than a standard 60Hz office monitor, ASUS has a perfect deal for you. The VA279QG is currently available for as little as $109, and for this money, you get quite a lot of a monitor. The ASUS VA279QG is a big 27-inch IPS monitor with a classic FullHD resolution and a wide 178-degree viewing angle. It can operate with a refresh rate of 120Hz, which is more than enough for buttery-smooth gaming. And since the monitor is FullHD, you will be able to see high refresh rates in more games since your GPU will have to render fewer pixels at 120Hz. Besides, the monitor supports variable refresh rate (VRR), a feature that can further reduce stutters by dynamically adjusting the refresh rate to your FPS. Other display specs include a 1ms MPRT response time, 16.7 million colors, 99% sRGB coverage, and a typical brightness of 300 nits. It is also covered with an anti-glare coating to reduce reflections. Ports-wise, you get one DisplayPort 1.2, one HDMI 1.4, one VGA, and one headphone jack. There are also two 2W speakers, but set your expectation right—these are unlikely to blow your mind with high-quality audio. Finally, there is a VESA 100 mount and a cutout in the base, which lets you mount your phone, namecard, or other small items for extra convenience. 27-inch ASUS VA279QG 120Hz IPS Gaming Monitor - $109 | 22% off on Amazon US This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. As an Amazon Associate, we earn from qualifying purchases.
    • lol See... one is only 100% when it's by itself. I live for exceptions to the rule... our talk point was in reference in comparing Vista (not SP1/2) release vs. 7. Any OS will run stable once enough work has been put into it... hell, even Windows 95 had six versions before she was finally complete(d)... just about, what, six or seven months before 98 became available?
  • Recent Achievements

    • Explorer
      treker_ed went up a rank
      Explorer
    • Apprentice
      CHUNWEI went up a rank
      Apprentice
    • Veteran
      1337ish went up a rank
      Veteran
    • Rookie
      john.al went up a rank
      Rookie
    • Week One Done
      patrickft456 earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      652
    2. 2
      ATLien_0
      269
    3. 3
      +FloatingFatMan
      176
    4. 4
      Michael Scrip
      155
    5. 5
      Steven P.
      136
  • Tell a friend

    Love Neowin? Tell a friend!