How can I merge two array from different n indexes?

Viewed 43

I have two array one contains length of 20 & second is in length of 10

I want to add 2 objects from the second array after every 5 object from first: in example

const array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
const secondArray = [a,b,c,d,e,f,g,h,i.j]

So expected output should be: [1,2,3,4,5,a,b,6,7,8,9,10,c,d...etc]
2 Answers

Loop from 5 to the length of array, with steps of 5.

Then use splice() to insert the first 2 items from secondArray at the current iterator

const array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
const secondArray = ['a','b','c','d','e','f','g','h','i','j'];
const result = [ ...array ];

for (let i = 5; i < array.length; i += 5) {
    result.splice(i, 2, ...secondArray.splice(0, 2))
}

console.log(result)

[
  1,
  2,
  3,
  4,
  5,
  "a",
  "b",
  8,
  9,
  10,
  "c",
  "d",
  13,
  14,
  15,
  "e",
  "f",
  18,
  19,
  20
]
const arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
const secondArray = ['a','b','c','d','e','f','g','h','i','j'];

const NR_CHUNK = 5;
const CHAR_CHUNK = 2;
const r = [];
for (let i = NR_CHUNK; i <= arr.length; i += NR_CHUNK) {
  r.push(...arr.slice(i - NR_CHUNK, i), ...secondArray.slice(((i/NR_CHUNK) * CHAR_CHUNK) - CHAR_CHUNK, ((i / NR_CHUNK) * CHAR_CHUNK)));
}

console.log(r);

Output:

[
  1,  2,  3,   4,   5,   'a', 'b', 6,
  7,  8,  9,   10,  'c', 'd', 11,  12,
  13, 14, 15,  'e', 'f', 16,  17,  18,
  19, 20, 'g', 'h'
]

This doesn't change your original arrays.

Related