Home > Back-end >  Merge three arrays in different iterations(incrementation) - JavaScript
Merge three arrays in different iterations(incrementation) - JavaScript

Time:11-17

I have three arrays of numbers:

const arr1 = [1, 2, 3, 4, 5, 6];
const arr2 = [10, 20];
const arr3 = [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000];

i want to join them in a way where every time 'n' numbers are added (n starts with 1..2..3..and so on) at first - one of each array, then 2 of each array, 3 of each untill the array is empty

so the final result should look like this:

finalArray = [1, 10, 100, 2, 3, 20, 200, 300, 4, 5, 6, 400, 500, 600, 700, 800, 900, 1000,];

i tried and tested a couple of nested loops methods but couldn't define the stop conditions, i just added all the numbers multiple times without success.

i tried using Concat(), but couldn't figure the right order


let finalArray = [];

for (let i = 0; i < arrF3.length; i  ) {
  finalArray.push(arrF3[i]);
  for (let j = 0; j < arrF2.length; j  ) {
    finalArray.push(arrF2[j]); 
    for (let k = 0; k < arrF1.length; k  ) {
      
    }
  }
}
console.table(finalArray);

Thanks in advance!

CodePudding user response:

Loop until the end of the longest length list, then take i 1 elements.

const arr1 = [1, 2, 3, 4, 5, 6];
const arr2 = [10, 20];
const arr3 = [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000];

const finalArray = [];

let totalI = 0;

for (let i = 0; i < Math.max(arr1.length, arr2.length, arr3.length); i  ) {
  finalArray.push(
    ...arr1.slice(totalI, totalI   i   1),
    ...arr2.slice(totalI, totalI   i   1),
    ...arr3.slice(totalI, totalI   i   1)
  );
  totalI  = i   1;
}

console.log(finalArray);

CodePudding user response:

This works for any number of arrays. Just keep slicing until all slices are empty.

const arrays = [
    [1, 2, 3, 4, 5, 6],
    [10, 20],
    [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]
]


let res = [], pos = 0, len = 1;

while (1) {
    let slices = arrays.map(a => a.slice(pos, pos   len))
    if (slices.every(s => s.length === 0))
        break
    res = res.concat(...slices)
    pos  = len
    len  = 1
}

console.log(...res)

  • Related