简体   繁体   中英

JAVASCRIPT add element of array to another array iterating

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!

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM