• 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

    • Arc 1.57.0 by Razvan Serea ARC browser is finally here for Windows, bringing its unique and modern approach to browsing. With a clean interface and a powerful sidebar, ARC makes managing tabs and organizing your workflow a breeze. You can group tabs, pin important pages, and quickly switch between work and personal spaces without clutter. It’s designed to be fast, customizable, and genuinely useful, making it more than just a browser—it’s a productivity tool. If you’re on Windows and want a fresh way to browse and stay organized, ARC is worth checking out. ARC browser key features: Split View: Work with multiple tabs side by side in a single window for efficient multitasking. Tab Grouping: Organize tabs into customizable groups for better workflow management. Pinned Tabs: Keep essential pages permanently accessible in the sidebar. Spaces: Create separate workspaces for different projects or personal use, reducing clutter. Sidebar Integration: Access bookmarks, notes, and tools directly from the sidebar for quick navigation. Customizable Themes: Personalize the browser’s appearance with themes and color schemes. Quick Search: Find tabs, history, or bookmarks instantly with a powerful search bar. Lightning-Fast Performance: Built for speed with optimized resource usage and minimal lag. Built-in Note-Taking: Jot down ideas or save snippets directly within the browser. Focus Mode: Hide distractions and focus on a single tab or task. Cross-Device Syncing: Seamlessly sync your data across multiple devices for a unified experience. Keyboard Shortcuts: Boost productivity with customizable shortcuts for common actions. AI-Powered Suggestions: Get smart recommendations for tabs, bookmarks, and workflows. Privacy Controls: Built-in tools for blocking trackers and managing cookies for enhanced security. Extensions Support: Compatible with popular browser extensions to extend functionality. Arc Browser 1.57.0 release notes: ''Thanks as always for using Arc. This week's release includes a bump to Chromium 137.0.7151.69, which patched three security vulnerabilities. Enjoy!'' Download: Arc Browser 1.57.0 | 1.9 MB (Freeware) View: Arc Browser Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • they put useless AI, new plastick sticker 8K and price +$80 for nothing
    • this AD block popup in annoying
  • Recent Achievements

    • First Post
      Uranus_enjoyer earned a badge
      First Post
    • Week One Done
      Uranus_enjoyer earned a badge
      Week One Done
    • Week One Done
      jfam earned a badge
      Week One Done
    • First Post
      survivor303 earned a badge
      First Post
    • Week One Done
      CHUNWEI earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      427
    2. 2
      +FloatingFatMan
      237
    3. 3
      ATLien_0
      213
    4. 4
      snowy owl
      207
    5. 5
      Xenon
      159
  • Tell a friend

    Love Neowin? Tell a friend!