将项目添加到一个数组后,再将其添加到另一个数组

时间:2018-08-07 15:45:36

标签: javascript arrays

基本上,我需要在一个数组中的每个元素之后添加另一个数组中的每个元素。因此,如果这是两个数组:

array1 = [
"item1",
"item2",
"item3",
"item4"
];

array2 = [
"choice1",
"choice2",
"choice3",
"choice4"
];

我需要让array1变成这个:

"item1",
"choice1",
"item2",
"choice2",
"item3",
"choice3",
"item4",
"choice4"
];

有人知道如何执行此操作吗?谢谢

5 个答案:

答案 0 :(得分:3)

鉴于数组的长度与您可以在其中一个数组上映射的长度相同,请提供一个数组的返回值,并在两个数组的索引处都包含两个值,然后使用concat展平以获得所需的结果。

[].concat.apply([], array1.map((i, ind) => [i,array2[ind]]));

let a1 = ["item1","item2","item3","item4"], a2 = ["choice1","choice2","choice3","choice4"],
combined_array = [].concat.apply([], a1.map((i, ind) => [i,a2[ind]]));

console.log(combined_array);

OR

您可以类似地使用reduce。如果您想避免从数组对象中调用concat,则可能是一个更好的选择:

array1.reduce((acc, i, ind) => acc.push(i, array2[ind])&&acc, []);

    let a1 = ["item1","item2","item3","item4"], a2 = ["choice1","choice2","choice3","choice4"],
    combined_array = a1.reduce((acc, i, ind) => acc.push(i, a2[ind])&&acc, []);
   

    console.log(combined_array);

答案 1 :(得分:2)

let array3 = [];
for(let i = 0; i < array1.length; i++){
  array3.push(array1[i]);
  array3.push(array2[i]);
}

答案 2 :(得分:2)

您可以使用forEach()遍历第一个数组。然后将当前项目推送到结果数组,并使用索引从第二个数组中提取该项目以推送为下一个项目:

var array1 = [
"item1",
"item2",
"item3",
"item4"
];

var array2 = [
"choice1",
"choice2",
"choice3",
"choice4"
];

var res = [];
array1.forEach((i,idx) =>{
  res.push(i);
  res.push(array2[idx]);
});
console.log(res);

答案 3 :(得分:1)

您可以遍历它们,并使用每个级别之后的元素的索引将它们添加到数组中:

array1 = [
  "item1",
  "item2",
  "item3",
  "item4"
];

array2 = [
  "choice1",
  "choice2",
  "choice3",
  "choice4"
];

var result = [];

for (var i = 0; i < array1.length; i++) {
  result.push(array1[i]);
  result.push(array2[i]);
}

console.log(result);

答案 4 :(得分:0)

您可以在此处使用push()方法,

array1 = [
"item1",
"item2",
"item3",
"item4"
];

array2 = [
"choice1",
"choice2",
"choice3",
"choice4"
];

var FinalArray = [];
for(var index = 0; index < array1.length; index++){
  FinalArray.push(array1[index]);
  FinalArray.push(array2[index]);
}