1

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 2

2

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
]
Sign up to request clarification or add additional context in comments.

4 Comments

It's removing the 6 & 7th index after adding the index from new array
I want to keep the 6 & 7 as well
Not sure what you mean. Please show the difference you want to see in my output
Okay got you thanks you so much I just spliced the array from i to 0 instead of 2 & it works as I want
0
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.