本文介绍了将项目添加到一个数组之后的另一个数组中的每个项目之后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Basically I need to add each item from one array after each on from another array. So if these are the two arrays:

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

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

我需要使array1变为:

I need to make array1 become this:

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

有人知道如何做吗?谢谢

Does anyone have any idea how to do this? Thanks

推荐答案

鉴于数组的长度与您可以映射到其中一个数组的长度相同,请使用这两个数组的索引处的两个值都相同,然后用concat展平以得到所需的结果。

Given that the arrays are the same length you can map over one of them, provide a return value of an array with both values at the index from both arrays, and then flatten with concat for your wanted result.

[].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 。如果您不想远离Array对象调用 concat ,这可能是一个更好的选择:

You could similarly use reduce. This may be a better option if you would like to keep away from calling concat off an Array object:

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

这篇关于将项目添加到一个数组之后的另一个数组中的每个项目之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 02:03