0

I have two arrays:

1) Array 1
[
  ['1', 'a', '1', 'b', '1', 'c', '1', 'd', '1', 'e', ​​'1', 'f', ' 1 ',' g ',' 1 ',' h '],
  ['2', 'a', '2', 'b', '2', 'c', '2', 'd', '2', 'e', ​​'2', 'f', ' 2 ',' g ',' 2 ',' h '],
  ...
]

2) Array 2
[1, 2, 3, 4, 5, 6, 7, 8...]

and now i need add each element of array 2 to the array 1:

[
 [
  '1', 1, 'a', '1', 2, 'b', '1', 3, 'c', '1', 4, 'd', '1', 5, 'e', ​​'1', 6, 'f', ' 1 ', 7, ' g ',' 1 ', 8, 'h'
 ], 
 [
  '2', 1, 'a', '2', 2, 'b', '2', 3, 'c', '2', 4, 'd', '2', 5 , 'e', ​​'2', 6, 'f', ' 2 ', 7, ' g ',' 2 ', 8, ' h '
 ],
 ... 
] 

Thanks!

2
  • is it important that the order of the final array is exactly like in your example? Commented Apr 22, 2020 at 19:51
  • Yes, it is! the final array must be exactly like this :( Commented Apr 22, 2020 at 19:52

2 Answers 2

1

You can use Array.splice to insert an element at a given position. If I'm not mistaken you want to insert the new elements at every 3th position, starting at 1. So you can define an offset and increase it by 3 after each iteration. Do this for every subelement of the array and you're done.

let arr = [ ['1', 'a', '1', 'b', '1', 'c', '1', 'd', '1', 'e','1','f', ' 1 ',' g ',' 1 ',' h '],
	    ['2', 'a', '2', 'b', '2', 'c', '2', 'd', '2', 'e','2', 'f', ' 2 ',' g ',' 2 ',' h '] ];

let arr2 = [1, 2, 3, 4, 5, 6, 7, 8];

let offset = 1;
for (let i of arr2)
{
	for (let k of arr)
	{
		k.splice (offset, 0, String (i));	
	}
	
	offset += 3;
}    	

console.log (arr);

Sign up to request clarification or add additional context in comments.

Comments

1

If you are trying to merge values from an array to another you might wan't to look at the concat() function.

const array1 = ['a', 'b', 'c'],
      array2 = ['d', 'e', 'f'],
      array3 = array1.concat(array2);

console.log(array3);
// expected output: Array ["a", "b", "c", "d", "e", "f"]

ref https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

2 Comments

But concat add elements to the last index of the array, or that i think
Yes, sorry i misunderstood.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.