-2

I have 2 Javascript arrays:

['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
['a', 'b', 'c']

I need to insert elements of second array into the first array every 4th or nth index of the first array, resulting in:

['a', '1', '2', '3', '4', 'b', '5', '6', '7', '8', 'c', '9', '10', '11', '12']

n needs to be a parameter, so I can move n to the 5th location, or 3rd location when needed.

Any solutions appreciated. ES6 ones would be great! Thank you in advance.

rew
  • 375
  • 2
  • 13

4 Answers4

1

Use a forEach with iterator as below:

let arr1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];
let arr2 = ['a', 'b', 'c'];

let index = 0;
arr2.forEach(function(v){
  arr1.splice(index, 0, v);
  index += 5;
});

console.log(arr1);

Now about the ES6, here is how I would write it:

let arr1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];
let arr2 = ['a', 'b', 'c'];

let index = 0;
Array.from(arr2).forEach((v)=>{
  arr1.splice(index, 0, v);
  index += 5;
});

console.log(arr1);
Jonathan Gagne
  • 4,241
  • 5
  • 18
  • 30
1

You can iterate through the smaller array using forEach use splice() to insert elements.

let arr1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
let arr2 = ['a', 'b', 'c']

function insertArr(arr1,arr2,n){
  arr1 = arr1.slice();
  arr2.forEach((a,i) => {
    arr1.splice(i*n+i,0,a);
  })
  return arr1;
}

console.log(insertArr(arr1,arr2,4))
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
1

Try this

b.forEach((itm, indx) => a.splice(Math.ceil(a.length/b.length)*indx, 0, itm));
Zeyad Etman
  • 2,250
  • 5
  • 25
  • 42
1

Iterate the 2nd array with Array.flatMap(), take the respective sequence from the 1st array with Array.slice(), and combine it with the current element using spread. Use Array.concat() with slice to add leftover items if any.

const fn = (n, added, target) =>
  added.flatMap((el, i) => [el, ...target.slice(n * i, n * (i + 1))])
  .concat(target.slice(n * added.length))

const arr1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
const arr2 = ['a', 'b', 'c']

console.log(JSON.stringify(fn(3, arr2, arr1)));
console.log(JSON.stringify(fn(4, arr2, arr1)));
console.log(JSON.stringify(fn(5, arr2, arr1)));
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • 1
    The first test case {console.log(JSON.stringify(fn(3, arr2, arr1)));}, truncates arr1. – rew Apr 22 '19 at 14:25