2

What's the best way to mix multiple arrays like the way in the image below,

PS:

  • I don't know what will be the length of each array

  • Arrays will contain +10000 elements

  • There will be more than 3 arrays

I made a solution for it but I'm looking for any better solution

mixing arrays

Here's my Own solution, I was looking for any better idea

import { compact, flattenDeep } from "lodash/array";

export const doTheMagic = master => {
  const longest = master.reduce((p, c, i, a) => (a[p].length > c.length ? p : i), 0);
  const mixed = master[longest].map((i, k) => {
    return master.map((o, a) => {
      if (master[a][k]) return master[a][k];
    });
  });
  const flaten = flattenDeep(mixed);
  return  compact(flaten);// to remove falsey values
};
const one = [1,2,3];
const two = ['a','b','c','d','e'];
const three = ['k','l','m','n'];
const mix = doTheMagic([one,two,three]);
console.log('mix: ', mix);
id3vz
  • 460
  • 4
  • 15

6 Answers6

2

You could use lodash for your solution.

const { flow, zip, flatten, filter} = _

const doTheMagic = flow(
  zip,
  flatten,
  filter
)

const one = [1, 2, 3]
const two = ['', '', '', '', '', '']
const three = ['foo', 'bar', 'wow', 'okay']

const result = doTheMagic(one, two, three)

console.log(result)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>

Works with different length of arrays and makes use of functional programming for elegant code.

Here's a codepen to run: https://codepen.io/matteodem/pen/mddQrwe

Matteo Demicheli
  • 174
  • 4
  • 13
0

This is my approach to achieve that, one for loop can make it. This will work if you don't know the number of arrays and array length as well.

function doTheMagic(arr){
  let ans = [];
  let maxLength = -1;
  
  arr.forEach((tempArr)=>{
    if(tempArr.length > maxLength){
      maxLength = tempArr.length;
    }
  })
  
  let l1=0,l2=0,l3=0;
  
  for(let i=0;i<maxLength;i++){
    arr.forEach((tempArr)=>{
      if(tempArr[i]){
        ans.push(tempArr[i]);
      }
    })

  }
  return ans;
}


let a1 = [1,2,3,4,5];
let a2 = ["","","","","",""];
let a3 = ['1','2','3','4','5'];


console.log(doTheMagic([a1,a2,a3]));
Akshay Bande
  • 2,491
  • 2
  • 12
  • 29
0

Here's my Own solution, I was looking for any better idea

import { compact, flattenDeep } from "lodash/array";

export const doTheMagic = master => {
  const longest = master.reduce((p, c, i, a) => (a[p].length > c.length ? p : i), 0);
  const mixed = master[longest].map((i, k) => {
    return master.map((o, a) => {
      if (master[a][k]) return master[a][k];
    });
  });
  const flaten = flattenDeep(mixed);
  return  compact(flaten);// to remove falsey values
};
const one = [1,2,3];
const two = ['a','b','c','d','e'];
const three = ['k','l','m','n'];
const mix = doTheMagic([one,two,three]);
console.log('mix: ', mix);
id3vz
  • 460
  • 4
  • 15
0

let a1 = [1, 2, 3, 4, 5];
let a2 = ["", "", "", "", "", ""];
let a3 = ['one', 'two', 'three', 'four', 'five'];

const doTheMagic = arrayOfArrays => {
  let maxLength = 0;
  let result = [];
  for (arr in arrayOfArrays) {
    maxLength = Math.max(maxLength, arrayOfArrays[arr].length);
  }
  for (let i = 0; i < maxLength; i++) {
    for (let j = 0; j < arrayOfArrays.length; j++) {
      if (arrayOfArrays[j][i]) {
        result.push(arrayOfArrays[j][i]);
      }
    }
  }
  return result;
}

console.log(doTheMagic([a1, a2, a3]));
bli07
  • 673
  • 1
  • 5
  • 16
0

This works with an unknown number of arrays, each one of unknown length :

const arrays = [
  [1, 2, 3, 4],
  ["a", "b", "c", "d", "e"],
  ["@", "#", "?"]
];

let output = [];

while (arrays.some(a => a.length)) { // While any of the arrays still has an element in it, keep going
  for (let a of arrays) {
    if (!a.length) continue;
    output.push(a.shift()); // remove the first element of the array and add it to output
  }
}

console.log(output)
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
0

Not sure if this is the better, but how you can write code that handles any number of arrays passed in.

const weave = (...args) =>  // convert arguments to an array
  args.reduce((res, arr, offset) => {  // loop over the arrays 
    arr.forEach((v, i) => res[offset + i * args.length] = v) // loop over array and add items to their indexes
    return res
  }, []).filter(x => x !== undefined) // remove the unused indexes


const one = [1, 2, 3]
const two = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
const three = ['w', 'x', 'y', 'z']
const result = weave(one, two, three)
console.log(result)

const result2 = weave(one, two)
console.log(result2)

const result3 = weave(one, two, three, ['*', '&'])
console.log(result3)
epascarello
  • 204,599
  • 20
  • 195
  • 236